views:

942

answers:

2

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!

+9  A: 

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"}}}'
drdaeman
Oh, I've almost forgot it... You should use `(',', ':')` as `separators` argument to json.dumps (see documentation). This will make data even more compact.
drdaeman
+1  A: 

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 )
Eli Courtwright
Just print'ing json.loads will print Python representation of the data, not JSON-encoded one.
drdaeman