JSON漂亮打印多行

ale*_*lex 1 python json

哪个命令行实用程序可以漂亮打印具有多行的文件(每个行以json编码)

输入文件:msgs.json:

[1,{"6":7,"4":5}]
[2,{"6":7,"4":5}]
Run Code Online (Sandbox Code Playgroud)

似乎json.tool只能使用单个JSON消息

编辑:在下面的答案修改了json.tool以支持多个JSON消息

示例用法:

python myjson.py msgs.json
                    [
                        1,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]
                    [
                        2,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]
Run Code Online (Sandbox Code Playgroud)

Gra*_*art 5

在python中做这样的事情:

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=(',', ': '))
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 1

myjson.py - 一个修改后的 json 工具,支持多个 JSON 消息:

#!/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()
Run Code Online (Sandbox Code Playgroud)