Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON pretty print multiple lines

Tags:

python

json

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
                        }
                    ]
like image 577
alex Avatar asked Jan 15 '14 20:01

alex


1 Answers

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=(',', ': ')))
like image 101
Graeme Stuart Avatar answered Nov 15 '22 04:11

Graeme Stuart