简体   繁体   中英

JSON pretty print multiple lines

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
                        }
                    ]

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=(',', ': ')))

jq can do this and a lot more, it's what I use but may be overkill for you. You can find it here .

cat yourfile.json | jq '.' should do the trick

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()

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM