Pretty print JSON python

Tom O' Mara picture Tom O' Mara · Apr 1, 2014 · Viewed 31.7k times · Source

if anybody with some knowledge about pretty printing JSON could help me with this I would be extremely grateful!

I'm looking to convert a complex python string into JSON format, using the function below to move the JSON string to a file:

with open('data.txt', 'wt') as out:
    pprint(string, stream=out)

The problem is that I'm getting syntax errors for the square brackets I believe, as this is a new topic for me and I can't figure out how to get around this. The JSON format I require is like this:

  {
        cols:[{id: 'Time', "label":"Time","type": "datetime"},
              {id: 'Time', "label":"Latency","type":"number"}],
        rows:[{c: [{v: %s}, {v: %s}]},
              {c: [{v: %s}, {v: %s}]}, 
              {c: [{v: %s}, {v: %s}]},
              {c: [{v: %s}, {v: %s}]}
              ]
    }

I'm following the Google Visualization API, you may be familier with it, but I need dynamic graphs. The above code is the format which the API requires to create a graph, so I am in the process of figuring out how to get my data from MYSQL into this format, so the graph can read and be displayed. The method I thought of was to update a file containing the required JSON format periodically, which is why the %s are present, however MartijnPeters suggests this is invalid.

Does anybody know the simplest way I can do this, or can you point me to any material which can help? Thank you!!

Answer

Martijn Pieters picture Martijn Pieters · Apr 1, 2014

You are writing Python representations, not JSON.

Use the json.dump() function to write pretty-printed JSON instead, directly to your file:

with open('data.txt', 'wt') as out:
    res = json.dump(obj, out, sort_keys=True, indent=4, separators=(',', ': '))