python中的漂亮打印json(pythonic方式)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23718896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:22:20  来源:igfitidea点击:

pretty-print json in python (pythonic way)

pythonjson

提问by autorun

I know that the pprintpython standard library is for pretty-printing python data types. However, I'm always retrieving json data, and I'm wondering if there is any easy and fast way to pretty-print json data?

我知道pprintpython 标准库用于漂亮地打印 python 数据类型。但是,我总是检索 json 数据,我想知道是否有任何简单快捷的方法来漂亮地打印 json 数据?

No pretty-printing:

没有漂亮的印刷:

import requests
r = requests.get('http://server.com/api/2/....')
r.json()

With pretty-printing:

漂亮的印刷:

>>> import requests
>>> from pprint import pprint
>>> r = requests.get('http://server.com/api/2/....')
>>> pprint(r.json())

回答by svvac

Python's builtin JSON modulecan handle that for you:

Python 的内置JSON 模块可以为您处理:

>>> 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"
}

回答by Holmes

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

回答by Anbraten

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:

我使用以下代码直接从我的请求获取结果中获取 json 输出,并在 python json 库函数 .dumps ()的帮助下通过使用缩进和对象键排序漂亮地打印了这个 json 对象:

import requests
import json

response = requests.get('http://example.org')
print (json.dumps(response.json(), indent=4, sort_keys=True))