How to prettyprint a JSON file?

前端 未结 13 990
滥情空心
滥情空心 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条回答
  •  萌比男神i
    2020-11-22 02:03

    Use this function and don't sweat having to remember if your JSON is a str or dict again - just look at the pretty print:

    import json
    
    def pp_json(json_thing, sort=True, indents=4):
        if type(json_thing) is str:
            print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
        else:
            print(json.dumps(json_thing, sort_keys=sort, indent=indents))
        return None
    
    pp_json(your_json_string_or_dict)
    

提交回复
热议问题