3

Original text file "chinese.txt" like following

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

on Mac run command in Terminal like following

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

The output is

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

How add parameter to avoid the "\u4f60\u597d" and get "你好"

What I like to do is the call API of Mapbox or HERE to find address of some location? The output of Mapbox or HERE is not pretty and I would like to use python -m json.tool to re-format their output and keep the Chinese characters not like the \uxxxx.

C.F. Wang
  • 33
  • 4

1 Answers1

2

This is the source for 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')

The problem is you have no way to add parameters to the call to json.dump - you'd want to do this instead:

json.dump(obj, outfile, sort_keys=sort_keys, indent=4, ensure_ascii=False)

But you'll have to write your own script for that, json.tool won't help you here.

Grismar
  • 20,449
  • 4
  • 26
  • 46