I am using the code below to dump a dictionary to a JSON file.
for i in result_set:
d = collections.OrderedDict()
d["id"]=i["id"]#id
d["name"]=i["name"]#name
json_data.append(d)
result_json=json.dumps(json_data,indent=None)
return result_json
the output of the file is as below
[{"id": "A", "name": "A Only"}, {"id": "B", "name": "B Only"} ]
how can i get the output in the format as below..
[{"id":"A","name":"A Only"},
{"id":"A","name":"B Only"}]
I have tried different indent values, with None, Negative and positive integers but it does not seem to work..
Any idea ??
CodePudding user response:
Quick and dirty: Load the json into a string (x) and do the following:
x = '[{"id": "A", "name": "A Only"}, {"id": "B", "name": "B Only"} ]'
x = '},\n'.join(x.split('},'))
print(x)
CodePudding user response:
If you expect to always format a list to JSON and you want to control the output to have newlines in specific places you may need to call json.dumps on invidual lines like this:
lines = (json.dumps(line) for line in json_data)
joined = ',\n'.join(lines)
result_json = f"[{joined}]"
