JSON漂亮打印多行

时间:2014-01-15 20:56:29

标签: python json

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

输入文件:msgs.json:

[1,{"6":7,"4":5}]
[2,{"6":7,"4":5}]

似乎json.tool仅适用于单个JSON消息

编辑:修改json.tool以在答案below

中支持多个JSON消息

示例用法:

python myjson.py msgs.json
                    [
                        1,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]
                    [
                        2,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]

3 个答案:

答案 0 :(得分: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=(',', ': '))

答案 1 :(得分:1)

jq可以做到这一点以及更多,这是我使用的,但对你来说可能有点矫枉过正。 你可以找到它here

cat yourfile.json | jq '.'应该做的伎俩

答案 2 :(得分: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()