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!
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
Syntax of json. First, use json. loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json. dumps() method is used.
Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.
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"}}}'
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With