如何从命令行漂亮地打印 JSON 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20265439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:05:16  来源:igfitidea点击:

How can I pretty-print a JSON file from the command line?

jsonshellcommand-line

提问by Luca Davanzo

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

我有一个包含一系列 JSON 元素的文件:

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

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

是否有用于格式化 JSON 以以可读形式显示文件内容的 shell 脚本?

I've seen thispost, 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"

Does anyone have any other ideas?

有没有人有其他想法?

回答by Shawn Vader

Pipe the results from the file into the python json tool 2.6 onwards

将文件中的结果通过管道传输到 python json 工具 2.6 以后

cat 'file_name' | python -m json.tool

回答by Fonebone

jq - a lightweight and flexible command-line JSON processor

jq - 轻量级灵活的命令行 JSON 处理器

I felt this deserved its own entry when it took me longer than it should have to discover. I was looking for a simple way to pretty-print the json output of docker inspect -f. It was mentioned briefly above by Noufal Ibrahim as part of another answer.

当我花了比它应该发现的时间更长的时间时,我觉得这值得自己进入。我正在寻找一种简单的方法来漂亮地打印 .json 文件的 json 输出docker inspect -f。Noufal Ibrahim 在上面简要提到了这一点,作为另一个答案的一部分。

From the jq website (https://stedolan.github.io/jq/):

从 jq 网站(https://stedolan.github.io/jq/):

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

jq 就像用于 JSON 数据的 sed - 您可以使用它来切片、过滤、映射和转换结构化数据,就像 sed、awk、grep 和朋友让您处理文本一样轻松。

It provides colored output by default and you simply have to pipe to jq, e.g.

它默认提供彩色输出,您只需通过管道连接到jq,例如

cat file | jq . 

Example:

例子:

"Raw" json outputvs the same piped to jq

“原始” json 输出vs相同的管道到 jq

回答by Nimrod007

You can use Python JSON tool (requires Python 2.6+).

您可以使用 Python JSON 工具(需要 Python 2.6+)。

For example:

例如:

echo '{ "element0" : "lorem", "element1" : "ipsum" }' | python -m json.tool

Which will give you:

这会给你:

{
    "element0": "lorem",
    "element1": "ipsum"
}

回答by Shubham Chaudhary

Colored output using Pygmentize + Python json.tool

使用 Pygmentize + Python json.tool 的彩色输出

Pygmentizeis a killer tool. See this.I combine python json.tool with pygmentize

Pygmentize是一个杀手级工具。看到这个。我将 python json.tool 与 pygmentize 结合使用

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

For other similar tools and installation instruction see the answer linked above.

对于其他类似的工具和安装说明,请参阅上面链接的答案。

Here is a live demo:

这是一个现场演示:

demo

演示

回答by Noufal Ibrahim

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

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

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

where pjson.pyis

这里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))

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

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

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.

OTOH,自定义代码是一种负担,所以有jq,在我看来它是黄金标准。它是用 C 编写的(因此是可移植的,没有 Python 或 Node 之类的依赖项),不仅打印漂亮而且速度快。

回答by srimaln91

You can use jqpackage which can be installed in all Linux systems. Install the tool using below commands.

您可以使用jq可以安装在所有 Linux 系统中的软件包。使用以下命令安装该工具。

# Redhat based systems(Centos)
yum install -y epel-release
yum install -y jq

# Debian based systems
apt install -y jq

Then you will be able to pipe text streams to the jq tool.

然后您将能够通过管道将文本流传输到 jq 工具。

echo '{"test":"value", "test2":"value2"}' | jq

Hope this answer will help.

希望这个答案会有所帮助。

回答by Chaklader Asfak Arefe

In the Mac OS, install jqwith the command,

在 Mac OS 中,jq使用命令安装,

$ brew install jq

You can get the pretty print JSON as similar as,

你可以得到类似的漂亮打印 JSON,

$ curl -X GET http://localhost:8080/api/v1/appointments/1  | jq


  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   117    0   117    0     0   8404      0 --:--:-- --:--:-- --:--:--  9000
{
  "craeted_at": "10:24:38",
  "appointment_date": "2019-02-08",
  "name_of_doctor": "Monika",
  "status": true,
  "price": 12.5,
  "id": 1
}

回答by Dave

Shawn's solution but for Python 3:

Shawn 的解决方案,但适用于 Python 3:

echo '{"foo": "bar"}' | python3 -m json.tool

回答by Nikhil Kumaran S

To format your JSON with proper indentation use JSON.stringify

使用适当的缩进格式化您的 JSON JSON.stringify

console.log(JSON.stringify(your_object, null, 2)); // prints in b/w

But to make it prettier by adding colors, you can check out my package beautify-json

但是为了通过添加颜色使其更漂亮,您可以查看我的包裹 beautify-json

beautify-json

美化-json

Example:

示例

const { jsonBeautify } = require('beautify-json')

let your_object = {
    name: 'Nikhil',
    age: 22,
    isMarried: false,
    girlfriends: null,
    interestedIn: [
        'javascript',
        'reactjs',
        'nodejs'
    ]
}

jsonBeautify(your_object) // It will beautify your object with colors and proper indentation and display it on the terminal

Output: Screenshot of the beautified object printed in terminal

输出在终端中打印的美化对象的屏幕截图

回答by Fábio A.

with python (2 and 3):

使用 python(2 和 3):

alias prettify_json="python -c 'import sys ;import json ; print(json.dumps(json.loads(sys.stdin.read()), indent=4))'"

or with ruby:

或用红宝石:

alias prettify_json="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""

you can use:

您可以使用:

echo '{"bar": "abc", "foo": "def"}' | prettify_json
curl http://.../file.json | prettify_json