使用 Python 将 JSON 数据漂亮地打印到文件 [英] Pretty-Print JSON Data to a File using Python

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

问题描述

一个课程项目涉及解析 Twitter JSON 数据.我正在获取数据并将其设置到文件中没有太多麻烦,但这一切都在一行中.这对于我正在尝试进行的数据操作来说很好,但是该文件非常难以阅读,而且我无法很好地检查它,这使得数据操作部分的代码编写变得非常困难.

A project for class involves parsing Twitter JSON data. I'm getting the data and setting it to the file without much trouble, but it's all in one line. This is fine for the data manipulation I'm trying to do, but the file is ridiculously hard to read and I can't examine it very well, making the code writing for the data manipulation part very difficult.

有谁知道如何在 Python 中执行此操作(即不使用我无法使用的命令行工具)?到目前为止,这是我的代码:

Does anyone know how to do that from within Python (i.e. not using the command line tool, which I can't get to work)? Here's my code so far:

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "wb")
# magic happens here to make it pretty-printed
twitterDataFile.write(output)
twitterDataFile.close()

注意我很感激人们向我指出 simplejson 文档等,但正如我所说,我已经看过它并继续需要帮助.一个真正有用的答复将比那里的例子更详细和解释性更强.谢谢

Note I appreciate people pointing me to simplejson documentation and such, but as I have stated, I have already looked at that and continue to need assistance. A truly helpful reply will be more detailed and explanatory than the examples found there. Thanks

还有:在 Windows 命令行中尝试此操作:

Also: Trying this in the windows command line:

more twitterData.json | python -mjson.tool > twitterData-pretty.json

结果如下:

Invalid control character at: line 1 column 65535 (char 65535)

我会给你我正在使用的数据,但它非常大,你已经看到了我用来制作文件的代码.

I'd give you the data I'm using, but it's very large and you've already seen the code I used to make the file.

推荐答案

您应该使用可选参数 indent.

You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

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

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