How to prettyprint a JSON file?

前端 未结 13 837
滥情空心
滥情空心 2020-11-22 01:53

I have a JSON file that is a mess that I want to prettyprint. What\'s the easiest way to do this in Python?

I know PrettyPrint takes an \"object\", which I think can

13条回答
  •  青春惊慌失措
    2020-11-22 02:12

    The json module already implements some basic pretty printing with the indent parameter that specifies how many spaces to indent by:

    >>> 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():

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

提交回复
热议问题