How to prettyprint a JSON file?

前端 未结 13 802
滥情空心
滥情空心 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:07

    I think that's better to parse the json before, to avoid errors:

    def format_response(response):
        try:
            parsed = json.loads(response.text)
        except JSONDecodeError:
            return response.text
        return json.dumps(parsed, ensure_ascii=True, indent=4)
    

提交回复
热议问题