漂亮的打印JSON python [英] Pretty print JSON python

查看:218
本文介绍了漂亮的打印JSON python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人对JSON的打印非常了解,那么我将不胜感激!

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

我正在使用以下函数将JSON字符串移动到文件中,以将复杂的python字符串转换为JSON格式:

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)

问题是我遇到了方括号的语法错误,因为这对我来说是个新话题,我不知道该如何解决.我需要的JSON格式如下:

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}]}
              ]
    }

我正在使用Google Visualization API,您可能对此比较熟悉,但是我需要动态图.上面的代码是API创建图形所需的格式,因此我正在弄清楚如何将MYSQL中的数据转换为这种格式,以便图形可以读取和显示.我想到的方法是定期更新包含所需JSON格式的文件,这就是为什么存在%s的原因,但是MartijnPeters认为这是无效的.

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

推荐答案

您正在编写 Python表示形式,而不是JSON.

You are writing Python representations, not JSON.

直接使用 json.dump()函数编写漂亮的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=(',', ': '))

这篇关于漂亮的打印JSON python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆