I have a json file json_file
which contains 2 records:
{"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:
{
"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:
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.
Your file has a JSON object on each line, which technically isn't a valid JSON syntax . You can work around that by loading each line individually with json.loads()
like this:
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
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.