python中的pretty-print json(pythonic方式) [英] pretty-print json in python (pythonic way)

查看:470
本文介绍了python中的pretty-print json(pythonic方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道pprint python标准库用于漂亮地打印python数据类型.但是,我一直在检索json数据,我想知道是否有任何简单快速的方法来漂亮地打印json数据?

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 any easy and fast way to pretty-print json data?

没有漂亮的印刷品

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

印刷精美:

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

推荐答案

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

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

这篇关于python中的pretty-print json(pythonic方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆