Skip to main content
 首页 » 编程设计

python之JSON pretty-print 多行

2025年05月04日13hnrainll

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

输入文件:msgs.json:

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

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

编辑:已修改 json.tool在答案中支持多个 JSON 消息 below

示例用法:

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

请您参考如下方法:

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