如何从命令行美丽打印JSON? (从文件) [英] How can I pretty-print JSON from the command line? (from a file)

查看:139
本文介绍了如何从命令行美丽打印JSON? (从文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json元素序列的文件:

I've a file with a sequence of json element:

{ element0: "lorem", value0: "ipsum" }
{ element1: "lorem", value0: "ipsum" }
...
{ elementN: "lorem", value0: "ipsum" }

是否有一个shell脚本来格式化JSON以便以可读的形式显示文件内容?

Is there a shell script to format JSON to display file content in a readable form?

我看过

I've seen this post, and I think is a good starting point!

我的想法是迭代文件中的行,然后:

My idea is to iterate rows in the file and then:

while read row; do echo ${row} | python -mjson.tool; done < "file_name"

有没有其他想法?

推荐答案

有很多。我个人有这个别名在我的 .zshrc

There are a bunch of them. I personally have this alias in my .zshrc

pjson () {
        ~/bin/pjson.py | less -X
}

其中 pjson.py

#!/usr/bin/env python

import json
import sys

try:
    input_str = sys.stdin.read()
    print json.dumps(json.loads(input_str), sort_keys = True, indent = 2)
except ValueError,e:
    print "Couldn't decode \n %s \n Error : %s"%(input_str, str(e))

允许我在命令行中使用它作为管道(类似 curl http:// ... 。| pjson )。

Allows me to use that in a command line as a pipe (something like curl http://.... | pjson).

OTOH,自定义代码是一种责任,因此有 jq ,对我来说看起来像黄金标准。它是用C语言编写的(因此是可移植的,没有依赖项,如Python或Node),不仅仅是漂亮的打印,而且快速。

OTOH, Custom code is a liability so there's jq, which to me looks like the gold standard. It's written in C (and is hence portable with no dependencies like Python or Node), does much more than just pretty printing and is fast.

这篇关于如何从命令行美丽打印JSON? (从文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆