Skip to content

Instantly share code, notes, and snippets.

@putalexey
Last active February 27, 2019 09:12
Show Gist options
  • Save putalexey/1c1261c0bef1eb6a2050fed07fcc061f to your computer and use it in GitHub Desktop.
Save putalexey/1c1261c0bef1eb6a2050fed07fcc061f to your computer and use it in GitHub Desktop.
Enhanced pythons json.tools script to print utf-8 chars
#!/usr/bin/env python
r"""Command-line tool to validate and pretty-print JSON
Usage::
$ echo '{"json":"obj"}' | python jsonformat.py
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python jsonformat.py
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
"""
import io
import sys
import json
import codecs
import errno
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = io.open(sys.argv[1], 'r', encoding='utf8')
# outfile = sys.stdout
outfile = sys.stdout = codecs.getwriter('utf8')(sys.stdout)
elif len(sys.argv) == 3:
infile = io.open(sys.argv[1], 'r', encoding='utf8')
outfile = io.open(sys.argv[2], 'wb')
# outfile = codecs.open('_{}'.format(sys.argv[2]), 'wb', encoding="utf-8")
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
obj = json.load(infile)
except ValueError as e:
raise SystemExit(e)
with outfile:
# with outfile:
try:
data = json.dumps(obj, sort_keys=True,
indent=4, separators=(',', ': '), ensure_ascii=False)
outfile.write(data.encode('utf8'))
except IOError as e:
if e.errno != errno.EPIPE:
raise e
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment