Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crunching json with python

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!

like image 718
Sergey Golovchenko Avatar asked Jun 24 '09 17:06

Sergey Golovchenko


People also ask

How do I parse a JSON in Python?

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.

How do I make JSON pretty in Python?

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.

Can Python be used with JSON?

Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.


2 Answers

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"}}}'
like image 145
drdaeman Avatar answered Oct 27 '22 06:10

drdaeman


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 )
like image 24
Eli Courtwright Avatar answered Oct 27 '22 06:10

Eli Courtwright