pretty-print json in python (pythonic way)

后端 未结 4 1871
闹比i
闹比i 2021-01-31 01:16

I know that the pprint python standard library is for pretty-printing python data types. However, I\'m always retrieving json data, and I\'m wondering if there is a

相关标签:
4条回答
  • 2021-01-31 01:50

    Python's builtin JSON module can handle that for you:

    >>> import json
    >>> a = {'hello': 'world', 'a': [1, 2, 3, 4], 'foo': 'bar'}
    >>> print(json.dumps(a, indent=2))
    {
      "hello": "world",
      "a": [
        1,
        2,
        3,
        4
      ],
      "foo": "bar"
    }
    
    0 讨论(0)
  • 2021-01-31 01:55
    import requests
    import json
    r = requests.get('http://server.com/api/2/....')
    pretty_json = json.loads(r.text)
    print (json.dumps(pretty_json, indent=2))
    
    0 讨论(0)
  • 2021-01-31 01:55

    Use for show unicode values and key.

    print (json.dumps(pretty_json, indent=2, ensure_ascii=False))
    
    0 讨论(0)
  • 2021-01-31 02:07

    I used following code to directly get a json output from my requests-get result and pretty printed this json object with help of pythons json libary function .dumps() by using indent and sorting the object keys:

    import requests
    import json
    
    response = requests.get('http://example.org')
    print (json.dumps(response.json(), indent=4, sort_keys=True))
    
    0 讨论(0)
提交回复
热议问题