Json string formatting with python

I would like to know if there is a way to format the resulting strings to bind any object to json in python. For example, suppose I have the following dictionary:

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

and the result of json encoding:

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

while I want:

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

Pay attention to the order of the elements and decimals of each number. Is there any way to do this?

Thanks in advance!

+4
source share
6 answers

You are trying to use JSON for something that it is not intended for, so it is not surprising that it does not work. You might consider using the source code of the Python json module as a starting point for your own output code, although it is probably easiest to start from scratch - it is not such a difficult task to write such an output function.

+2
source

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

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

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

+9
source

For Python, as well as JSON, the order inside the dict is irrelevant. Use lists instead of dicts if you don't mind.

If you only want to order JSON output (ie, prefer {1:0, 2:0} over {2:0, 1:0} , even if they are equivalent), you can use collections.OrderedDict , which will remember the order insert elements.

+2
source

You can change the way you organize your floats by placing them in a custom class and overriding the __repr__ method, for example:

 import json class CustomFloat(float): def __repr__(self): return "%.3g" % self D = {'a': CustomFloat(12.73874), 'b': CustomFloat(1.74872), 'c': CustomFloat(8.27495)} print json.dumps(D, indent=2) 

Fingerprints:

 { "a": 12.7, "c": 8.27, "b": 1.75 } 

This solves half your question, at least.

+2
source

Try sort_keys=True with json.dumps or json.JSONEncoder.__init__ . For instance,

 >>> import json >>> d = {'a': 'Apple', 'b': Banana, 'c': 'Pepsi'} >>> print json.dumps(d) {"a": "Apple", "c": "Pepsi", "b": "Banana} >>> print json.dumps(d, sort_keys=True) {"a": "Apple", "b": "Banana, "c": "Pepsi"} 
+1
source
 import json from collections import OrderedDict d = {'a': 12.73874, 'b': 1.74872, 'c': 8.27495} L = sorted(d.items(), key=lambda x: x[1], reverse=True) # sort by float value print(json.dumps(OrderedDict((k, round(v, 2)) for k, v in L), indent=4)) 

Output

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

Alternatively you can use yaml , an example .

+1
source

All Articles