繁体   English   中英

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

[英]Pretty-Print JSON Data to a File using Python

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

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

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

您可以解析 JSON,然后使用如下缩进再次输出它:

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

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

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() 它也更快。

您可以使用 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)

如果您正在生成新的 *.json 或修改现有的 josn 文件,请使用“缩进”参数来获得漂亮的 json 格式。

import json
responseData = json.loads(output)
with open('twitterData.json','w') as twitterDataFile:    
    json.dump(responseData, twitterDataFile, indent=4)

如果您已经有想要漂亮格式化的现有 JSON 文件,则可以使用以下命令:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()
import json
def writeToFile(logData, fileName, openOption="w"):
  file = open(fileName, openOption)
  file.write(json.dumps(json.loads(logData), indent=4)) 
  file.close()  

您可以将文件重定向到 python 并使用该工具打开并阅读它使用更多。

示例代码将是,

cat filename.json | python -m json.tool | more

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM