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

时间:2019-03-29 19:59:04

标签: python json

我有一个json文件json_file,其中包含2条记录:

{"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}

如何使用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}
    ]
}

2 个答案:

答案 0 :(得分:1)

由于您的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))

然后,我们创建您所需的数据结构,并将json的每一行附加到该数据结构。

答案 1 :(得分:0)

您的文件在每一行上都有一个JSON对象,从技术上来说,该对象不是有效的JSON syntax。您可以通过以下方式解决此问题:分别用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
        }
    ]
}