Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print JSON python

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!!

like image 653
Tom O' Mara Avatar asked Apr 01 '14 17:04

Tom O' Mara


People also ask

What is pretty-print JSON?

Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .

How do I print to JSON in Python?

Convert from Python to JSON If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.


1 Answers

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=(',', ': '))
like image 169
Martijn Pieters Avatar answered Sep 24 '22 00:09

Martijn Pieters