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

发布于 2025-01-03 06:57:28 字数 941 浏览 1 评论 0原文

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

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

A project for class involves parsing Twitter JSON data. 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 (i.e. not using the command line tool, which I can't get to work)? 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. A truly helpful reply will be more detailed and explanatory than the examples found there. Thanks

Also:
Trying this in the windows command line:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

仄言 2025-01-10 06:57:28

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

You should use the optional argument 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)
    )
混浊又暗下来 2025-01-10 06:57:28

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

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

请参阅 http://docs.python.org/library/ json.html 了解更多信息。

You can parse the JSON, then output it again with indents like this:

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

See http://docs.python.org/library/json.html for more info.

臻嫒无言 2025-01-10 06:57:28
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() 即可。它也更快。

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(). It's faster too.

最终幸福 2025-01-10 06:57:28

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

You can use json module of python to pretty print.

>>> 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)
放低过去 2025-01-10 06:57:28

如果您要生成新的 *.json 或修改现有的 josn 文件,请使用“indent”参数以获得漂亮的视图 json 格式。

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

If you are generating new *.json or modifying existing josn file the use "indent" parameter for pretty view json format.

import json
responseData = json.loads(output)
with open('twitterData.json','w') as twitterDataFile:    
    json.dump(responseData, twitterDataFile, indent=4)
你在看孤独的风景 2025-01-10 06:57:28

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

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

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()
还如梦归 2025-01-10 06:57:28
import json
def writeToFile(logData, fileName, openOption="w"):
  file = open(fileName, openOption)
  file.write(json.dumps(json.loads(logData), indent=4)) 
  file.close()  
import json
def writeToFile(logData, fileName, openOption="w"):
  file = open(fileName, openOption)
  file.write(json.dumps(json.loads(logData), indent=4)) 
  file.close()  
べ繥欢鉨o。 2025-01-10 06:57:28

您可以将文件重定向到 python 并使用该工具打开并使用 more 来读取它。

示例代码将是,

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

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文