How to save in a json file with each key on a different line

advertisements

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]}


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)