简体   繁体   English

如何重新格式化JSON文件以包含数组

[英]How can I reformat a JSON file to contain an array

I have a json file json_file which contains 2 records: 我有一个包含2条记录的json文件json_file

{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null}
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}

How can I reformat the file using python to make it have one array like this: 如何使用python重新格式化文件,使其具有一个这样的数组:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

As your json file is invalid, we need to read it line by line: 由于您的json文件无效,我们需要逐行读取它:

import json

input_file = """{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null}
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}"""

output_dict = dict()
output_dict['foo'] = list()

for line in input_file.split('\n'):
    json_line = json.loads(line)
    output_dict['foo'].append(json_line)
print(json.dumps(output_dict, indent=2))

Then we create your desired data structure, and append each line of json to that data structure. 然后,我们创建您所需的数据结构,并将json的每一行附加到该数据结构。

Your file has a JSON object on each line, which technically isn't a valid JSON syntax . 您的文件在每行上都有一个JSON对象,从技术上来说,这不是有效的JSON语法 You can work around that by loading each line individually with json.loads() like this: 您可以通过以下方式解决此问题:分别使用json.loads()加载每一行,如下所示:

import json

json_filename = 'json_file'

with open(json_filename) as file:
    array = {'foo': []}
    foo_list = array['foo']
    for line in file:
        obj = json.loads(line)
        foo_list.append(obj)

print(json.dumps(array, indent=4))
{
    "foo": [
        {
            "name": "XYZ",
            "address": "54.7168,94.0215",
            "country_of_residence": "PQR",
            "countries": "LMN;PQRST",
            "date": "28-AUG-2008",
            "type": null
        },
        {
            "name": "OLMS",
            "address": null,
            "country_of_residence": null,
            "countries": "Not identified;No",
            "date": "23-FEB-2017",
            "type": null
        }
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM