简体   繁体   English

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

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

A project for class involves parsing Twitter JSON data.类项目涉及解析 Twitter JSON 数据。 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.这对于我正在尝试进行的数据操作来说很好,但是该文件非常难以阅读,而且我无法很好地检查它,这使得数据操作部分的代码编写变得非常困难。

Does anyone know how to do that from within Python (ie not using the command line tool, which I can't get to work)?有谁知道如何从 Python 中做到这一点(即不使用命令行工具,我无法开始工作)? 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()

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.请注意,我感谢人们将我指向 simplejson 文档等,但正如我所说,我已经看过它并继续需要帮助。 A truly helpful reply will be more detailed and explanatory than the examples found there.一个真正有用的答复将比那里的例子更详细和解释性更强。 Thanks谢谢

Also: Trying this in the windows command line:另外:在windows命令行中尝试这个:

more twitterData.json | python -mjson.tool > twitterData-pretty.json

results in this:结果如下:

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.我会给你我正在使用的数据,但它非常大,你已经看到了我用来制作文件的代码。

You should use the optional argument indent .您应该使用可选参数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()

You can parse the JSON, then output it again with indents like this:您可以解析 JSON,然后使用如下缩进再次输出它:

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

See http://docs.python.org/library/json.html for more info.有关更多信息,请参阅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)

You don't need json.dumps() if you don't want to parse the string later, just simply use json.dump() .如果您不想稍后解析字符串,则不需要json.dumps() ,只需使用json.dump() It's faster too.它也更快。

You can use json module of python to pretty print.您可以使用 python 的json模块进行漂亮的打印。

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

So, in your case所以,在你的情况下

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

If you are generating new *.json or modifying existing josn file the use "indent" parameter for pretty view json format.如果您正在生成新的 *.json 或修改现有的 josn 文件,请使用“缩进”参数来获得漂亮的 json 格式。

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

If you already have existing JSON files which you want to pretty format you could use this:如果您已经有想要漂亮格式化的现有 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()  

You could redirect a file to python and open using the tool and to read it use more.您可以将文件重定向到 python 并使用该工具打开并阅读它使用更多。

The sample code will be,示例代码将是,

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

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

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