Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - 如何相印JSON文件?(How to prettyprint a JSON file?)

I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python?

(我有一个JSON文件是一个混乱,我想漂亮 - 在python中最简单的方法是什么?)

I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.

(我知道PrettyPrint带有一个“对象”,我认为它可以是一个文件,但我不知道如何传入文件 - 只是使用文件名不起作用。)

  ask by Colleen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The json module already implements some basic pretty printing with the indent parameter:

(json模块已经使用indent参数实现了一些基本的漂亮打印:)

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

To parse a file, use json.load() :

(要解析文件,请使用json.load() :)

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...