漂亮的打印 JSON python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22792848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:41:47  来源:igfitidea点击:

Pretty print JSON python

pythonjsonstringgoogle-visualizationpprint

提问by Tom O' Mara

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

如果任何对漂亮打印 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:

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

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:

问题是我认为方括号出现语法错误,因为这对我来说是一个新主题,我不知道如何解决这个问题。我需要的JSON格式是这样的:

  {
        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.

我正在关注 Google Visualization API,您可能更熟悉它,但我需要动态图。上面的代码是 API 创建图形所需的格式,所以我正在研究如何将我的数据从 MYSQL 获取到这种格式,以便图形可以读取和显示。我想到的方法是定期更新包含所需 JSON 格式的文件,这就是 %s 存在的原因,但是 MartijnPeters 建议这是无效的。

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

有没有人知道我能做到的最简单的方法,或者你能指出任何可以帮助我的材料吗?谢谢!!

采纳答案by Martijn Pieters

You are writing Python representations, not JSON.

您正在编写Python 表示,而不是 JSON。

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

使用该json.dump()函数将漂亮打印的 JSON 直接写入您的文件:

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