小编典典

使用 Python 将 JSON 数据漂亮地打印到文件中

all

一个类项目涉及解析 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)

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


阅读 44

收藏
2022-08-17

共1个答案

小编典典

您应该使用可选参数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()
2022-08-17