首页 > 解决方案 > 如何将一个 json 文件中的 json 元素存储到另一个 json 文件中?

问题描述

我有一个 json 文件。这是它的外观示例:

*{
            "_id": "5f70aa5c04d7a034fc19e8969b000599",
            "contributors": null,
            "coordinates": null,
            "created_at": "Wed May 06 09:32:46 +0000 2020",
            "display_text_range": [
                13,
                35
            ],
            "entities": {
                "hashtags": [],
                "symbols": [],
                "urls": [],
                "user_mentions": [
                    {
                        "id": 1213834918263869400,
                        "id_str": "1213834918263869442",
                        "indices": [
                            0,
                            12
                        ],
                        "name": "D!@n@(ام علي)",
                        "screen_name": "Dianamh2312"
                    }
                ]
            },
            "favorite_count": 0,
            "favorited": false,
            "filter_level": "low",
            "geo": null,
            "id": 1257966527946473500,
            "id_str": "1257966527946473472",
            "in_reply_to_screen_name": "Dianamh2312",
            "in_reply_to_status_id": 1257909535752310800,
            "in_reply_to_status_id_str": "1257909535752310784",
            "in_reply_to_user_id": 1213834918263869400,
            "in_reply_to_user_id_str": "1213834918263869442",
            "is_quote_status": false,
            "lang": "ar",
            "place": {
                "attributes": {},
                "bounding_box": {
                    "coordinates": [
                        [
                            [
                                150.520929,
                                -34.118347
                            ],
                            [
                                150.520929,
                                -33.578141
                            ],
                            [
                                151.343021,
                                -33.578141
                            ],
                            [
                                151.343021,
                                -34.118347
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "country": "Australia",
                "country_code": "AU",
                "full_name": "Sydney, New South Wales",
                "id": "0073b76548e5984f",
                "name": "Sydney",
                "place_type": "city",
                "url": "https://api.twitter.com/1.1/geo/id/0073b76548e5984f.json"
            },
            "quote_count": 0,
            "reply_count": 0,
            "retweet_count": 0,
            "retweeted": false,
            "source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
            "text": "@Dianamh2312 يسعد اوقاتك ام علي ",
            "timestamp_ms": "1588757566807",
            "truncated": false,
            "user": {
                "contributors_enabled": false,
                "created_at": "Mon Dec 11 11:29:28 +0000 2017",
                "default_profile": true,
                "default_profile_image": false,
                "description": "اَللّـهُمَّ اكْشِفْ هذِهِ الْغُمَّةَ عَنْ هذِهِ الاُْمَّةِ بِحُضُورِهِ ، وَ عَجِّلْ لَنا ظُهُورَهُ ، اِنَّهُمْ يَرَوْنَهُ بَعيداً وَ نَراهُ قَريباً.",
                "favourites_count": 8338,
                "follow_request_sent": null,
                "followers_count": 5208,
                "following": null,
                "friends_count": 5097,
                "geo_enabled": true,
                "id": 940181735601455100,
                "id_str": "940181735601455106",
                "is_translator": false,
                "lang": null,
                "listed_count": 0,
                "location": null,
                "name": "iman",
                "notifications": null,
                "profile_background_color": "F5F8FA",
                "profile_background_image_url": "",
                "profile_background_image_url_https": "",
                "profile_background_tile": false,
                "profile_banner_url": "https://pbs.twimg.com/profile_banners/940181735601455106/1584734762",
                "profile_image_url": "http://pbs.twimg.com/profile_images/1246607950392840192/QmN6Qf50_normal.jpg",
                "profile_image_url_https": "https://pbs.twimg.com/profile_images/1246607950392840192/QmN6Qf50_normal.jpg",
                "profile_link_color": "1DA1F2",
                "profile_sidebar_border_color": "C0DEED",
                "profile_sidebar_fill_color": "DDEEF6",
                "profile_text_color": "333333",
                "profile_use_background_image": true,
                "protected": false,
                "screen_name": "Hageiman",
                "statuses_count": 4607,
                "time_zone": null,
                "translator_type": "none",
                "url": null,
                "utc_offset": null,
                "verified": false
            }
        },
        {
            "_id": "5f70aa5c04d7a034fc19e8969b0007dd",
            "contributors": null,
            "coordinates": null,
            "created_at": "Wed May 06 09:33:34 +0000 2020",
            "display_text_range": [
                12,
                33
            ],
            "entities": {
                "hashtags": [],
                "symbols": [],
                "urls": [],
                "user_mentions": [
                    {
                        "id": 1099969756805906400,
                        "id_str": "1099969756805906434",
                        "indices": [
                            0,
                            11
                        ],
                        "name": "jamal199",
                        "screen_name": "jamal19918"
                    }
                ]
            },
            "favorite_count": 0,
            "favorited": false,
            "filter_level": "low",
            "geo": null,
            "id": 1257966726299316200,
            "id_str": "1257966726299316230",
            "in_reply_to_screen_name": "jamal19918",
            "in_reply_to_status_id": 1257937052097745000,
            "in_reply_to_status_id_str": "1257937052097744896",
            "in_reply_to_user_id": 1099969756805906400,
            "in_reply_to_user_id_str": "1099969756805906434",
            "is_quote_status": false,
            "lang": "ar",
            "place": {
                "attributes": {},
                "bounding_box": {
                    "coordinates": [
                        [
                            [
                                150.520929,
                                -34.118347
                            ],
                            [
                                150.520929,
                                -33.578141
                            ],
                            [
                                151.343021,
                                -33.578141
                            ],
                            [
                                151.343021,
                                -34.118347
                            ]
                        ]
                    ],
                    "type": "Polygon"
                },
                "country": "Australia",
                "country_code": "AU",
                "full_name": "Sydney, New South Wales",
                "id": "0073b76548e5984f",
                "name": "Sydney",
                "place_type": "city",
                "url": "https://api.twitter.com/1.1/geo/id/0073b76548e5984f.json"
            },
            "quote_count": 0,
            "reply_count": 0,
            "retweet_count": 0,
            "retweeted": false,
            "source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
            "text": "@jamal19918 صباح النور jamal ",
            "timestamp_ms": "1588757614098",
            "truncated": false,
            "user": {
                "contributors_enabled": false,
                "created_at": "Mon Dec 11 11:29:28 +0000 2017",
                "default_profile": true,
                "default_profile_image": false,
                "description": "اَللّـهُمَّ اكْشِفْ هذِهِ الْغُمَّةَ عَنْ هذِهِ الاُْمَّةِ بِحُضُورِهِ ، وَ عَجِّلْ لَنا ظُهُورَهُ ، اِنَّهُمْ يَرَوْنَهُ بَعيداً وَ نَراهُ قَريباً.",
                "favourites_count": 8339,
                "follow_request_sent": null,
                "followers_count": 5208,
                "following": null,
                "friends_count": 5097,
                "geo_enabled": true,
                "id": 940181735601455100,
                "id_str": "940181735601455106",
                "is_translator": false,
                "lang": null,
                "listed_count": 0,
                "location": null,
                "name": "iman",
                "notifications": null,
                "profile_background_color": "F5F8FA",
                "profile_background_image_url": "",
                "profile_background_image_url_https": "",
                "profile_background_tile": false,
                "profile_banner_url": "https://pbs.twimg.com/profile_banners/940181735601455106/1584734762",
                "profile_image_url": "http://pbs.twimg.com/profile_images/1246607950392840192/QmN6Qf50_normal.jpg",
                "profile_image_url_https": "https://pbs.twimg.com/profile_images/1246607950392840192/QmN6Qf50_normal.jpg",
                "profile_link_color": "1DA1F2",
                "profile_sidebar_border_color": "C0DEED",
                "profile_sidebar_fill_color": "DDEEF6",
                "profile_text_color": "333333",
                "profile_use_background_image": true,
                "protected": false,
                "screen_name": "Hageiman",
                "statuses_count": 4608,
                "time_zone": null,
                "translator_type": "none",
                "url": null,
                "utc_offset": null,
                "verified": false
            }
        },*

我正在编写一个基本的json脚本来从这个文件中获取数据,其中lang="ar" 代码如下:

 var fs = require('fs');
fs.readFile('./instance3_u.json', 'utf8', (err, jsonString) => {
    if (err) {
        console.log("Error reading file from disk:", err)
        return
    }
    try {
        const db = JSON.parse(jsonString)
        var count = Object.keys(db.docs).length;

        for (var i = 0; i < count; i++) {
            if (db.docs[i].lang === "ar") {
            console.log(db.docs[i]._id, '\n', db.docs[i].text, '\n', db.docs[i].place.bounding_box.coordinates[0][0], '\n', db.docs[i].lang, '\n')
                var data_ar = {
                    id: db.docs[i]._id,
                    text: db.docs[i].text,
                    coordinates: db.docs[i].place.bounding_box.coordinates[0][0],
                    lang: db.docs[i].lang
                }
                var data = JSON.stringify(data_ar)
                fs.writeFileSync('data_ar.json', data);
            }
            
        }
       
    }
    catch (err) {
        console.log('Error parsing JSON string:', err)
    }
})

控制台打印所需的输出。当我尝试将此输出存储到另一个名为data_ar的 json 文件中时,它只是给了我i的最后一个值。我想存储我在控制台中打印的全部数据

我如何实现这一目标?

标签: arraysnode.jsjson

解决方案


fs.writeFileSync('data_ar.json', data);每次调用时,此行都会创建该 data_ar.json 文件。所以这就是为什么你只看到数组中的最后一个。您应该改用fs.appendFileSync方法。

编辑:正如评论中所问的,在第一个示例中创建的 JSON 无效。为了使其有效,它需要是一个数组。创建数组的更简单方法是过滤和映射原始数组,然后您可以使用writeFileSync,因为您只需执行 1 次写入操作。

const data = db.docs.filter(d=> d.lang === "ar").map(d=>
                ({
                    id: d._id,
                    text: d.text,
                    coordinates: d.place.bounding_box.coordinates[0][0],
                    lang: d.lang
                  }));

    fs.writeFileSync('data_ar.json', data);

推荐阅读