原始文本文件“chinese.txt”如下
{"type":"FeatureCollection","text":"你好"}
在 Mac 上,在终端中运行命令,如下所示
$ cat chinese.txt | python -m json.tool
输出是
{
"text": "\u4f60\u597d",
"type": "FeatureCollection"
}
如何添加参数以避免“\u4f60\u597d”并得到“你好”
我喜欢做的是从 shell 中使用
python -m json.tool
,而不修改 json.tool
的代码。一个常见的用例是重新格式化 UTF-8 编码的 json 文件,并保留中文字符,而不是像 \uxxxx。
这是 json.tool 的来源:
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(),
help='a JSON file to be validated or pretty-printed')
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
help='write the output of infile to outfile')
parser.add_argument('--sort-keys', action='store_true', default=False,
help='sort the output of dictionaries alphabetically by key')
options = parser.parse_args()
infile = options.infile or sys.stdin
outfile = options.outfile or sys.stdout
sort_keys = options.sort_keys
with infile:
try:
obj = json.load(infile)
except ValueError as e:
raise SystemExit(e)
with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
问题是你无法向
json.dump
的调用添加参数 - 你想要这样做:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4, ensure_ascii=False)
但是您必须为此编写自己的脚本,
json.tool
在这里对您没有帮助。