Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json string formatting with python

I'd like to know if there is any way to format the resulting strings of the enconding of some object with json in python. For example, suppose I have the following dictionary:

{'a': 12.73874, 'b': 1.74872, 'c': 8.27495}

and the result of the json encoding is:

{
    "c": 8.27495,
    "b": 1.74872,
    "a": 12.73874
}

while the result I want is:

{
    "a": 12.74,
    "c": 8.28,
    "b": 1.75
}

Notice the order of the elements and the decimal places of each number. Is there any way to do this?

Thanks in advance!

like image 906
Alberto A Avatar asked Jul 26 '12 14:07

Alberto A


1 Answers

If you are using 2.6+, you can use do this:

print json.dumps(jsonStr, sort_keys=True, indent=2, separators=(',', ': '))

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

like image 154
onetwopunch Avatar answered Sep 28 '22 02:09

onetwopunch