I had to look at a 9-MB json file this weekend. Here’s how I converted it from one-line to indented multi-line:
$ sudo apt-get install python-simplejson $ dpkg -L python-simplejson $ less /usr/share/pyshared/simplejson/tests/test_pass1.py $ python >>> import simplejson as json >>> f = open (big.json, 'r') >>> oneline = f.read () >>> f.close >>> ds = json.loads (oneline) # ds = "data structure" >>> multiline = json.dumps (ds, indent=" ") # two spaces / indent level >>> f = open (formatted.json, 'w') >>> f.write (multiline) >>> f.close () >>> ^D $
In reviewing the steps for this blog post, I note that there is also a “load” function, that might be even easier.
>>> import simplejson as json >>> dir (json) ['Decimal', 'JSONDecodeError', 'JSONDecoder', 'JSONEncoder',\ 'OrderedDict', '__all__', '__author__', '__builtins__', '__doc__',\ '__file__', '__name__', '__package__', '__path__', '__version__',\ '_default_decoder', '_default_encoder', '_import_OrderedDict',\ '_import_c_make_encoder', '_speedups', '_toggle_speedups',\ 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'ordered_dict',\ 'scanner'] >>>
Example input:
[{'pk': '5', 'model': 'theModel', 'fields': {'two': 'two', 'one': 'one'}}]
Example output:
[ { "pk": "5", "model": "theModel", "fields": { "two": "two", "one": "one" } } ]