2020年8月9日 / 67次阅读 / Last Modified 2020年8月12日
python标准库json模块内有一个tool工具,可以用来验证json数据,并对json数据进行美化输出。
$ python3.8 -m json.tool msg.json
{
"fromaddr": "from@qq.com",
"passwd": "123456789",
"server": "smtp.qq.com",
"port": 587,
"connect": "tls",
"msg": [
{
"subject": "test json file",
"to": "to@qq.com",
"cc": null,
"bcc": null,
"content": "hahaha...lalala..."
},
{
"subject": "test json file",
"to": "to@qq.com",
"cc": null,
"bcc": null,
"content": "2222...hahaha...lalala..."
}
]
}
json.tool工具还有两个参数:--sort-key和--json-lines,具体请用-h查看说明。
json.tool的源码很简单,具体如下:
r"""Command-line tool to validate and pretty-print JSON
Usage::
$ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
"""
import argparse
import json
import sys
def main():
prog = 'python -m json.tool'
description = ('A simple command line interface for json module '
'to validate and pretty-print JSON objects.')
parser = argparse.ArgumentParser(prog=prog, description=description)
parser.add_argument('infile', nargs='?',
type=argparse.FileType(encoding="utf-8"),
help='a JSON file to be validated or pretty-printed',
default=sys.stdin)
parser.add_argument('outfile', nargs='?',
type=argparse.FileType('w', encoding="utf-8"),
help='write the output of infile to outfile',
default=sys.stdout)
parser.add_argument('--sort-keys', action='store_true', default=False,
help='sort the output of dictionaries alphabetically by key')
parser.add_argument('--json-lines', action='store_true', default=False,
help='parse input using the jsonlines format')
options = parser.parse_args()
infile = options.infile
outfile = options.outfile
sort_keys = options.sort_keys
json_lines = options.json_lines
with infile, outfile:
try:
if json_lines:
objs = (json.loads(line) for line in infile)
else:
objs = (json.load(infile), )
for obj in objs:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
except ValueError as e:
raise SystemExit(e)
if __name__ == '__main__':
try:
main()
except BrokenPipeError as exc:
sys.exit(exc.errno)
-- EOF --
本文链接:https://www.pynote.net/archives/2332
《用json.tool验证和美化json数据》有3条留言
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记
json的string如果太长,貌似没有换行语法(string内的\n不算),如果为了看着舒服一点,可以使用array of strings。 [ ]
json.dump(s)函数,就是美化输出。 [ ]
阅读源码,学习--sort-key和--json-lines这两个参数的含义。 [ ]