Tutorial :Crunching json with python



Question:

Echoing my other question now need to find a way to crunch json down to one line: e.g.

{"node0":{      "node1":{          "attr0":"foo",          "attr1":"foo bar",          "attr2":"value with        long        spaces"      }  }}  

would like to crunch down to a single line:

{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with        long        spaces"}}}  

by removing insignificant white spaces and preserving the ones that are within the value. Is there a library to do this in python?

EDIT Thank you both drdaeman and Eli Courtwright for super quick response!


Solution:1

http://docs.python.org/library/json.html

>>> import json  >>> json.dumps(json.loads("""  ... {"node0":{  ...     "node1":{  ...         "attr0":"foo",  ...         "attr1":"foo bar",  ...         "attr2":"value with        long        spaces"  ...     }  ... }}  ... """))  '{"node0": {"node1": {"attr2": "value with        long        spaces", "attr0": "foo", "attr1": "foo bar"}}}'  


Solution:2

In Python 2.6:

import json  print json.loads( json_string )  

Basically, when you use the json module to parse json, then you get a Python dict. If you simply print a dict and/or convert it to a string, it'll all be on one line. Of course, in some cases the Python dict will be slightly different than the json-encoded string (such as with booleans and nulls), so if this matters then you can say

import json  print json.dumps( json.loads(json_string) )  

If you don't have Python 2.6 then you can use the simplejson module. In this case you'd simply say

import simplejson  print simplejson.loads( json_string )  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »