Json string formatting with python

23,614

Solution 1

You are trying to use JSON for something it's not intended for, so it's no surprise it does not work well. You could consider to use the source code of Python's json module as a starting point for your own output code, though it is probably easiest to start from scratch – it's not that complex a task to write such an output function.

Solution 2

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

Solution 3

You can change the way your floats are serialized by putting them in a custom class and overriding the __repr__ method, like this:

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)

This prints:

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

This solves half of your question at least.

Solution 4

For Python as well as JSON, the order within a dict bears no meaning. Use lists instead of dicts if you mind.

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

Solution 5

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
}

As an alternative you could use yaml, example.

Share:
23,614
Alberto A
Author by

Alberto A

Updated on March 08, 2020

Comments

  • Alberto A
    Alberto A about 4 years

    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!

    • Sven Marnach
      Sven Marnach almost 12 years
      What JSON ecnoder are you using? The one that is shipped with Python, or simplejson, or yet another one?
    • mgilson
      mgilson almost 12 years
      I thought the point of JSON was to be able to restore the object you feed it exactly. In this case, if you truncate after the decimal point, you can no longer restore the dictionary from JSON (although sorting is a different story)
    • Alberto A
      Alberto A almost 12 years
      I'm using the json that is shipped with python. I think the problem here isn't with json itself but with the purpose I'm using json for. I'm using it not as a way to be able to exactly restore the objects I encode (restoring the object isn't even important in the context of my application), but as a way to easily record them in a human readable way. That's why the decimal places and the order matter. But I suppose that it will be simpler if I print the file myself, instead of using json :)
    • jfs
      jfs almost 12 years
      note: both "%.2f" % v and round(v, 2) produce 8.27 for v = 8.27495, not 8.28.
  • Alberto A
    Alberto A almost 12 years
    I've already tried that. The problem is, I don't need the contents of the dictionary in lexicographical order, I need them in an order I specify. In my case, what I need to print is X, Y, Z, Azimuth, Elevation and Roll (the contents of the dictionary), and I want it to be printed in this order. If I use sort_keys, I have the order: Azimuth, elevation, roll, X, Y, Z
  • tiwo
    tiwo almost 12 years
  • Sam Mussmann
    Sam Mussmann almost 12 years
    That bug looks like it was fixed in December of 2010: hg.python.org/cpython/rev/64a97c4ebadc
  • jfs
    jfs almost 12 years
    The issue6105 provides a workaround for earlier versions: json.encoder.c_make_encoder = None before .dumps().
  • Alberto A
    Alberto A almost 12 years
    Yes, you're right. That's what I'll end up doing, since, like you said, it's not a hard task at all.
  • ccpizza
    ccpizza almost 8 years
    A better option might be to use the built-in ast module: docs.python.org/2/library/ast.html