如何用Python打印JSON文件?
当前回答
这里有一个简单的例子,可以用Python将JSON以一种很好的方式打印到控制台,而不需要将JSON作为本地文件存储在计算机上:
import pprint
import json
from urllib.request import urlopen # (Only used to get this example)
# Getting a JSON example for this example
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read()
# To print it
pprint.pprint(json.loads(text))
其他回答
使用这个函数,不用担心,你必须再次记住你的JSON是str还是dict-看看漂亮的打印:
import json
def pp_json(json_thing, sort=True, indents=4):
if type(json_thing) is str:
print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
else:
print(json.dumps(json_thing, sort_keys=sort, indent=indents))
return None
pp_json(your_json_string_or_dict)
我认为最好先解析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)
为了能够从命令行进行漂亮的打印并能够控制缩进等,您可以设置类似于以下内容的别名:
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
使用json.dump()或json.dumps()的indent关键字参数指定要使用的缩进量:
>>> import json
>>>
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
要解析文件,请使用json.load():
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
您可以尝试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
输出
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 查询JSON类型内的数组元素
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if