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

查看:391
本文介绍了使用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.

推荐答案

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天全站免登陆