如何用Python打印JSON文件?
当前回答
我认为最好先解析json,以避免错误:
def format_response(response):
try:
parsed = json.loads(response.text)
except JSONDecodeError:
return response.text
return json.dumps(parsed, ensure_ascii=True, indent=4)
其他回答
使用pprint:https://docs.python.org/3.6/library/pprint.html
import pprint
pprint.pprint(json)
print()与pprint.pprint()比较
print(json)
{'feed': {'title': 'W3Schools Home Page', 'title_detail': {'type': 'text/plain', 'language': None, 'base': '', 'value': 'W3Schools Home Page'}, 'links': [{'rel': 'alternate', 'type': 'text/html', 'href': 'https://www.w3schools.com'}], 'link': 'https://www.w3schools.com', 'subtitle': 'Free web building tutorials', 'subtitle_detail': {'type': 'text/html', 'language': None, 'base': '', 'value': 'Free web building tutorials'}}, 'entries': [], 'bozo': 0, 'encoding': 'utf-8', 'version': 'rss20', 'namespaces': {}}
pprint.pprint(json)
{'bozo': 0,
'encoding': 'utf-8',
'entries': [],
'feed': {'link': 'https://www.w3schools.com',
'links': [{'href': 'https://www.w3schools.com',
'rel': 'alternate',
'type': 'text/html'}],
'subtitle': 'Free web building tutorials',
'subtitle_detail': {'base': '',
'language': None,
'type': 'text/html',
'value': 'Free web building tutorials'},
'title': 'W3Schools Home Page',
'title_detail': {'base': '',
'language': None,
'type': 'text/plain',
'value': 'W3Schools Home Page'}},
'namespaces': {},
'version': 'rss20'}
使用json标准库模块读取数据后,使用pprint标准库模块显示解析的数据。例子:
import json
import pprint
json_data = None
with open('file_name.txt', 'r') as f:
data = f.read()
json_data = json.loads(data)
pprint.pprint(json_data)
输出将如下所示:
{'address': {'city': 'New York',
'postalCode': '10021-3100',
'state': 'NY',
'streetAddress': '21 2nd Street'},
'age': 27,
'children': [],
'firstName': 'John',
'isAlive': True,
'lastName': 'Smith'}
请注意,此输出不是有效的JSON;虽然它以良好的格式显示Python数据结构的内容,但它使用Python语法来实现。特别是,字符串(通常)用单引号括起来,而JSON需要双引号。要将数据重写为JSON文件,请使用pprint.pdf格式:
pretty_print_json = pprint.pformat(json_data).replace("'", '"')
with open('file_name.json', 'w') as f:
f.write(pretty_print_json)
一个非常简单的方法是使用rich。使用此方法,您还可以突出显示json
此方法从名为config.json的json文件中读取数据
from rich import print_json
setup_type = open('config.json')
data = json.load(setup_type)
print_json(data=data)
您可以尝试pprintjson。
安装
$ pip3 install pprintjson
用法
使用pprintjson CLI从文件中精确打印JSON。
$ pprintjson "./path/to/file.json"
使用pprintjson CLI从stdin打印JSON。
$ echo '{ "a": 1, "b": "string", "c": true }' | pprintjson
使用pprintjson CLI从字符串中精确打印JSON。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }'
从缩进为1的字符串中精确打印JSON。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -i 1
从字符串中精确打印JSON并将输出保存到文件output.JSON。
$ pprintjson -c '{ "a": 1, "b": "string", "c": true }' -o ./output.json
输出
为了能够从命令行进行漂亮的打印并能够控制缩进等,您可以设置类似于以下内容的别名:
alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"
然后以以下方式之一使用别名:
cat myfile.json | jsonpp
jsonpp < myfile.json
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- Ajax会调用什么样的响应,比如'for (;;);{json data}的意思?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本