'How to save to a JSON file with each key on a different line
When I save data to a JSON file it will look like this:
{'Gri33415': ['Griffiths', 2015, 'Gold', 35, 35000], 'Smi22316': ['Smith', 2016, 'Silver', 3, 7500], 'Mia56213': ['Miah', 2013, 'Platinum', 140, 165000]}
How ever I would like each key to be on a different line like this:
{"Gri33415": ["Griffiths", 2015, "Gold", 35, 40000],
"Smi22316": ["Smith", 2016, "Silver", 3, 7500],
"Mia56213": ["Miah", 2013, "Platinum", 140, 165000]}
Solution 1:[1]
From the official docs: Pretty printing
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
... indent=4, separators=(',', ': '))
{
"4": 5,
"6": 7
}
Edit 1
If you only want new lines for keys (e.g. not after every comma) you could solve that via some clever regex trickery. Live Demo
import json
import re
s = json.dumps({'4': 5, '6': [1, 2, 3, 4]}, sort_keys=True)
s = re.sub(r',\s*"', ',\n"', s)
s = '{\n' + s[1:-1] + '\n}'
print(s)
Solution 2:[2]
You can add the indent option when you write out to get pretty print outfile.
import json
with open('your_file.json', 'r') as infile:
data = json.load(infile)
with open('new_json.json', 'w') as outfile:
outfile.write(json.dumps(data, indent=4, sort_keys=True))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mike Tung |
