首页 > 解决方案 > 如何重新格式化 JSON 文件以包含数组

问题描述

我有一个json_file包含 2 条记录的 json 文件:

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

标签: pythonjson

解决方案


由于您的 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 附加到该数据结构。


推荐阅读