使用 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)

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

193127 次浏览

您可以解析 JSON,然后再次输出缩进,如下所示:

import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)

有关更多信息,请参见 http://docs.python.org/library/json.html

可以使用 python 的 Json模块进行漂亮打印。

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}

对你来说

>>> print json.dumps(json_output, indent=4)

您应该使用可选参数 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 并使用该工具打开,然后使用更多工具读取它。

示例代码将是,

cat filename.json | python -m json.tool | more
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()

如果你已经有现有的 JSON 文件,你想要漂亮的格式,你可以使用这个:

    with open('twitterdata.json', 'r+') as f:
data = json.load(f)
f.seek(0)
json.dump(data, f, indent=4)
f.truncate()

如果您正在生成 new * . json 或修改现有的 josn 文件,请使用“ indent”参数作为 pretty view json 格式。

import json
responseData = json.loads(output)
with open('twitterData.json','w') as twitterDataFile:
json.dump(responseData, twitterDataFile, indent=4)
import json
def writeToFile(logData, fileName, openOption="w"):
file = open(fileName, openOption)
file.write(json.dumps(json.loads(logData), indent=4))
file.close()