Skip to content

Instantly share code, notes, and snippets.

@stg7
Created November 6, 2016 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stg7/47089f2588f9b59f2418467603e90cdd to your computer and use it in GitHub Desktop.
Save stg7/47089f2588f9b59f2418467603e90cdd to your computer and use it in GitHub Desktop.
Prints a json string in a pretty formatted output on stdout
#!/usr/bin/env python3
"""
Prints a json string in a pretty formatted output on stdout.
Example call:
echo "{\"a\":100, \"b\": [1,2,3]}" | ./json_prettifier.py
will print:
{
"a": 100,
"b": [
1,
2,
3
]
}
"""
import json
import sys
obj = ""
for l in sys.stdin:
obj += l
jobj = obj.strip()
if jobj == "":
sys.exit(0)
try:
j = json.loads(jobj)
print(json.dumps(j, indent=4, sort_keys=True))
except Exception as e:
print('error: ' + str(e) + str(jobj), file=sys.stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment