python -m json.tool 输出中文
python -m json.tool to output Chinese
原始文本文件"chinese.txt"如下
{"type":"FeatureCollection","text":"你好"}
在终端中的 Mac 运行 命令如下
$ cat chinese.txt | python -m json.tool
输出为
{
"text": "\u4f60\u597d",
"type": "FeatureCollection"
}
如何添加参数来避免“\u4f60\u597d”而得到“你好”
我喜欢做的是调用API Mapbox 或 HERE 来查找某个位置的地址? Mapbox 或 HERE 的输出不漂亮,我想使用 python -m json.tool 来重新格式化它们的输出并保持汉字不像 \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
在这里帮不了您。
原始文本文件"chinese.txt"如下
{"type":"FeatureCollection","text":"你好"}
在终端中的 Mac 运行 命令如下
$ cat chinese.txt | python -m json.tool
输出为
{
"text": "\u4f60\u597d",
"type": "FeatureCollection"
}
如何添加参数来避免“\u4f60\u597d”而得到“你好”
我喜欢做的是调用API Mapbox 或 HERE 来查找某个位置的地址? Mapbox 或 HERE 的输出不漂亮,我想使用 python -m json.tool 来重新格式化它们的输出并保持汉字不像 \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
在这里帮不了您。