0

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}
 ]
}
martineau
124k29 gold badges180 silver badges318 bronze badges
asked Mar 29, 2019 at 19:59
1
  • 5
    Your input file is not valid JSON - JSON allows for one top-level object. Commented Mar 29, 2019 at 20:02

2 Answers 2

1

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.

answered Mar 29, 2019 at 20:07
Sign up to request clarification or add additional context in comments.

Comments

1

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
 }
 ]
}
answered Mar 29, 2019 at 20:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.