如何相印JSON文件?

本文翻译自:How to prettyprint a JSON file?

I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? 我有一个JSON文件是一个混乱,我想漂亮 - 在python中最简单的方法是什么? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work. 我知道PrettyPrint带有一个“对象”,我认为它可以是一个文件,但我不知道如何传入文件 - 只是使用文件名不起作用。


#1楼

参考:https://stackoom.com/question/sJHH/如何相印JSON文件


#2楼

The json module already implements some basic pretty printing with the indent parameter: json模块已经使用indent参数实现了一些基本的漂亮打印:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

To parse a file, use json.load() : 要解析文件,请使用json.load()

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

#3楼

You can do this on the command line: 您可以在命令行上执行此操作:

python3 -m json.tool < some.json

(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion). (正如在问题的评论中已经提到的,感谢@Kai Petzke提出的python3建议)。

Actually python is not my favourite tool as far as json processing on the command line is concerned. 实际上,就命令行上的json处理而言,python不是我最喜欢的工具。 For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. 对于简单漂亮的打印是可以的,但如果你想操纵json它可能会变得过于复杂。 You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing. 你很快就需要编写一个单独的脚本文件,你最终可能会得到一些键是你的“某些键”(python unicode)的地图,这使得选择字段变得更加困难并且不会真正朝着漂亮的方向发展 - 印刷。

I use jq . 我用jq The above can be done with: 以上可以通过以下方式完成:

jq . some.json

and you get colors as a bonus (and way easier extendability). 并且您将颜色作为奖励(并且更容易扩展)。

Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. 附录:关于一方面使用jq处理大型JSON文件,另一方面使用非常大的jq程序的评论中存在一些混淆。 For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. 对于漂亮打印由单个大型JSON实体组成的文件,实际限制是RAM。 For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). 对于漂亮打印由单个真实数据阵列组成的2GB文件,漂亮打印所需的“最大驻留集大小”为5GB(无论是使用jq 1.5还是1.6)。 Note also that jq can be used from within python after pip install jq . 另请注意,在pip install jq之后可以在python中使用pip install jq


#4楼

Pygmentize + Python json.tool = Pretty Print with Syntax Highlighting Pygmentize + Python json.tool =使用语法突出显示的漂亮打印

Pygmentize is a killer tool. Pygmentize是一种杀手级工具。 See this. 看到这个。

I combine python json.tool with pygmentize 我将python json.tool与pygmentize结合起来

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json

See the link above for pygmentize installation instruction. 有关pygmentize安装说明,请参阅上面的链接。

A demo of this is in the image below: 这个演示如下图所示:

演示


#5楼

Use this function and don't sweat having to remember if your JSON is a str or dict again - just look at the pretty print: 使用此功能,不要再记得你的JSON是否是strdict - 只需看看漂亮的印刷品:

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)

#6楼

To be able to pretty print from the command line and be able to have control over the indentation etc. you can set up an alias similar to this: 为了能够从命令行进行漂亮打印并能够控制缩进等,您可以设置类似于此的别名:

alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"

And then use the alias in one of these ways: 然后以下列方式之一使用别名:

cat myfile.json | jsonpp
jsonpp < myfile.json
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值