Reputation: 1917
which command line utility can pretty-print a file with multiple lines (each encoded in json)
input file: msgs.json:
[1,{"6":7,"4":5}]
[2,{"6":7,"4":5}]
it seems that json.tool works only with a single JSON message
EDIT: modified json.tool to support multiple JSON msgs in the answer below
example usage:
python myjson.py msgs.json
[
1,
{
"4": 5,
"6": 7
}
]
[
2,
{
"4": 5,
"6": 7
}
]
Upvotes: 6
Views: 14657
Reputation: 11
A command line utility to pretty-print a line-delimited JSON file (aka NDJSON, LDJSON, JSON Lines, JSON-L, JSONL) that is available for anyone with a modern version of Python:
python -m json.tool msgs.json --json-lines
jq is more powerful and flexible beyond just pretty-printing, so it it's worth installing and using it like this:
cat msgs.json | jq .
Upvotes: 1
Reputation: 6063
In python do something like this:
import json
with open('msgs.json', 'r') as json_file:
for row in json_file:
data = json.loads(row)
print(json.dumps(data, sort_keys=True, indent=2, separators=(',', ': ')))
Upvotes: 9
Reputation: 1917
myjson.py - a modified json tool to support multiple JSON messages:
#!/usr/bin/python
"""myjson.py: Command-line tool to validate and pretty-print JSON
Usage::
1) $ echo '{"json":"obj"}' | python myjson.py
{
"json": "obj"
}
2) $ echo '{ 1.2:3.4}' | python myjson.py
Expecting property name enclosed in double quotes: line 1 column 2 (char 2)
3) printing a file with multiple lines where each line is a JSON message:
e.g. msgs.json:
[1,,{"6":7,"4":5}]
[2,{"6":7,"4":5}]
python myjson.py msgs.json
[
1,
{
"4": 5,
"6": 7
}
]
[
2,
{
"4": 5,
"6": 7
}
]
"""
import sys
import json
def main():
data = []
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
for line in infile:
data.append(json.loads(line))
except ValueError, e:
raise SystemExit(e)
with outfile:
for d in data:
json.dump(d, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
outfile.write('\n')
if __name__ == '__main__':
main()
Upvotes: 1