使用Python将JSON数据美化输出到文件
我有一个课堂项目,需要解析Twitter的JSON数据。我已经成功获取数据并保存到文件里,但所有内容都在一行上。这对我进行数据处理来说没问题,但文件看起来实在太难读了,我很难检查内容,这让编写处理数据的代码变得非常困难。
有没有人知道怎么在Python里做到这一点?也就是说,不使用命令行工具,因为我搞不定那个。以下是我目前的代码:
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的文档,但正如我所说,我已经看过了,还是需要帮助。一个真正有用的回复应该比那里的例子更详细和解释清楚。谢谢
另外: 在Windows命令行中尝试这个:
more twitterData.json | python -mjson.tool > twitterData-pretty.json
结果是这样的:
Invalid control character at: line 1 column 65535 (char 65535)
我本来想给你们我使用的数据,但数据量太大了,而且你们已经看过我用来生成文件的代码。
8 个回答
118
import json
with open("twitterdata.json", "w") as twitter_data_file:
json.dump(output, twitter_data_file, indent=4, sort_keys=True)
如果你不打算以后解析这个字符串,那么就不需要使用 json.dumps()
,直接用 json.dump()
就可以了。这样做也更快。
134
你可以先解析这个JSON数据,然后再像这样输出带缩进的格式:
import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)
想了解更多信息,可以查看这个链接:http://docs.python.org/library/json.html。
176
你可以使用一个可选的参数 indent
。
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
with open("twitterData.json", "w") as twitterDataFile:
# magic happens here to make it pretty-printed
twitterDataFile.write(
simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True)
)