Pythonmjson.tool工具输出中文

2024-04-24 17:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

“原始文本文件”中文.txt“就像跟在后面一样

{"type":"FeatureCollection","text":"你好"}

在Mac终端上运行如下命令

$ cat chinese.txt | python -m json.tool

输出为

{
    "text": "\u4f60\u597d",
    "type": "FeatureCollection"
}

如何添加参数以避免“\u4f60\u597d”并获得“你好”

我喜欢做的是调用Mapbox的API还是在这里找到某个位置的地址?Mapbox或HERE的输出不是很好,我想使用python-mjson.tool工具重新格式化其输出,并保留与\uxxx不同的中文字符。你知道吗


Tags: text命令txtjson终端mactypetool
1条回答
网友
1楼 · 发布于 2024-04-24 17:29:32

这就是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在这里帮不了你。你知道吗

相关问题 更多 >