Pretty print JSON python

梦想与她 提交于 2019-11-27 12:27:57

问题


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


回答1:


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=(',', ': '))


来源:https://stackoverflow.com/questions/22792848/pretty-print-json-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!