[英]How can I reformat a JSON file to contain an array
我有一个包含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}
如何使用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}
]
}
由于您的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的每一行附加到该数据结构。
您的文件在每行上都有一个JSON对象,从技术上来说,这不是有效的JSON语法 。 您可以通过以下方式解决此问题:分别使用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.