Linux 中处理 JSON 数据的命令 jq

在 Linux 中,jq 是一个用于处理 JSON 数据的命令行工具。它具有强大的功能,可以帮助你从 JSON 数据中提取特定的信息、进行数据转换和格式化输出等。

在 Linux 中,jq 是一个用于处理 JSON 数据的命令行工具。它具有强大的功能,可以帮助你从 JSON 数据中提取特定的信息、进行数据转换和格式化输出等。以下将简单介绍 jq 工具的安装和使用:

安装

在大多数 Linux 发行版上,可以使用包管理器进行安装。例如,在 Ubuntu 上使用如下命令进行安装

sudo apt install jq

安装详细日志如下:

hxstrive@localhost:~$ sudo apt install jq
[sudo] password for hx:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libjq1 libonig5
The following NEW packages will be installed:
  jq libjq1 libonig5
0 upgraded, 3 newly installed, 0 to remove and 29 not upgraded.
Need to get 357 kB of archives.
After this operation, 1087 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://archive.ubuntu.com/ubuntu jammy/main amd64 libonig5 amd64 6.9.7.1-2build1 [172 kB]
Get:2 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 libjq1 amd64 1.6-2.1ubuntu3.1 [133 kB]
Get:3 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 jq amd64 1.6-2.1ubuntu3.1 [52.5 kB]
Fetched 357 kB in 3s (132 kB/s)
Selecting previously unselected package libonig5:amd64.
(Reading database ... 42858 files and directories currently installed.)
Preparing to unpack .../libonig5_6.9.7.1-2build1_amd64.deb ...
Unpacking libonig5:amd64 (6.9.7.1-2build1) ...
Selecting previously unselected package libjq1:amd64.
Preparing to unpack .../libjq1_1.6-2.1ubuntu3.1_amd64.deb ...
Unpacking libjq1:amd64 (1.6-2.1ubuntu3.1) ...
Selecting previously unselected package jq.
Preparing to unpack .../jq_1.6-2.1ubuntu3.1_amd64.deb ...
Unpacking jq (1.6-2.1ubuntu3.1) ...
Setting up libonig5:amd64 (6.9.7.1-2build1) ...
Setting up libjq1:amd64 (1.6-2.1ubuntu3.1) ...
Setting up jq (1.6-2.1ubuntu3.1) ...
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.10) ...

使用 jq --help 命令验证安装是否成功:

hxstrive@localhost:~$ jq --help
jq - commandline JSON processor [version 1.6]

Usage:  jq [options] <jq filter> [file...]
        jq [options] --args <jq filter> [strings...]
        jq [options] --jsonargs <jq filter> [JSON_TEXTS...]

jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.
jq 是一款用于处理 JSON 输入的工具,它会对 JSON 文本输入应用给定的过滤器,并将过滤器的结果以 JSON 格式输出到标准输出。

The simplest filter is ., which copies jq's input to its output
unmodified (except for formatting, but note that IEEE754 is used
for number representation internally, with all that that implies).
最简单的过滤器是.,它会将jq的输入原封不动地复制到输出(除了格式之外,但要注意内部使用IEEE754来表示数字,这意味着其带来的所有影响)。

For more advanced filters see the jq(1) manpage ("man jq")
and/or https://stedolan.github.io/jq
有关更高级的过滤器,请参阅jq(1)手册页(“man jq”)和/或https://stedolan.github.io/jq

Example:

        $ echo '{"foo": 0}' | jq .
        {
                "foo": 0
        }

Some of the options include:
  -c               compact instead of pretty-printed output; 紧凑输出而非格式化输出
  -n               use `null` as the single input value; 使用 `null` 作为单一输入值;
  -e               set the exit status code based on the output; 根据输出设置退出状态码;
  -s               read (slurp) all inputs into an array; apply filter to it;  将所有输入读取( slurps )到一个数组中;对其应用过滤器;
  -r               output raw strings, not JSON texts;  输出原始字符串,而非JSON文本;
  -R               read raw strings, not JSON texts; 读取原始字符串,而非JSON文本;
  -C               colorize JSON;  为JSON着色;
  -M               monochrome (don't colorize JSON); 单色(不对JSON进行着色);
  -S               sort keys of objects on output; 在输出时对对象的键进行排序;
  --tab            use tabs for indentation; 使用制表符进行缩进;
  --arg a v        set variable $a to value <v>; 将变量$a设置为值 <v>;
  --argjson a v    set variable $a to JSON value <v>; 将变量$a设置为JSON值 <v>;
  --slurpfile a f  set variable $a to an array of JSON texts read from <f>; 将变量$a设置为从<f>读取的JSON文本数组;
  --rawfile a f    set variable $a to a string consisting of the contents of <f>; 将变量$a设置为包含<f>内容的字符串;
  --args           remaining arguments are string arguments, not files;  剩余的参数是字符串参数,而非文件;
  --jsonargs       remaining arguments are JSON arguments, not files;  剩余的参数是JSON参数,而非文件;
  --               terminates argument processing; 终止参数处理;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].
命名参数也可通过 $ARGS.named[] 获取,而位置参数可通过 $ARGS.positional[] 获取。

See the manpage for more options.

在 CentOS 上的安装命令如下:

sudo yum install jq

基本用法

在用户主目录的 test 目录下创建一个名为 data.json 文件,用于后续做测试,如下:

hxstrive@localhost:~$ mkdir test
hxstrive@localhost:~$ cd test
hxstrive@localhost:~/test$ vim data.json
hxstrive@localhost:~/test$ cat data.json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}

使用jq命令输出整个 JSON 内容:

hxstrive@localhost:~/test$ jq . data.json
{
  "name": "John",
  "age": 30,
  "city": "New York"
}

提取name字段的值:

hxstrive@localhost:~/test$ jq .name data.json
"John"

提取name和age字段的值:

hxstrive@localhost:~/test$ jq '{name:.name, age:.age}' data.json
{
  "name": "John",
  "age": 30
}

高级用法

假设有一个包含多个对象的 JSON 数组文件array.json:

[
  {
    "id": 1,
    "name": "Alice"
  },
  {
    "id": 2,
    "name": "Bob"
  }
]

提取数组第一个对象的 name 字段:

hxstrive@localhost:~/test$ jq '.[0].name' array.json
"Alice"

提取所有对象的name字段:

hxstrive@localhost:~/test$ jq '.[].name' array.json
"Alice"
"Bob"

过滤数据,只输出 id 大于等于 2 的对象:

hxstrive@localhost:~/test$ jq '.[] | select(.id >= 2)' array.json
{
  "id": 2,
  "name": "Bob"
}

选项示例

以下是使用 jq 命令处理 array.json 文件的各种选项示例:

  • -c 选项:紧凑输出

hxstrive@localhost:~/test$ jq -c '.' array.json
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
  • -n 选项:使用 null 作为输入

hxstrive@localhost:~/test$ jq -n 'null'
null
  • -e 选项:根据输出设置退出状态码

# 当条件为真时,退出码为0
hxstrive@localhost:~/test$ jq -e '.[] | select(.id == 1)' array.json > /dev/null
hxstrive@localhost:~/test$ echo $?
0

# 当条件为假时,退出码为1
hxstrive@localhost:~/test$ jq -e '.[] | select(.id == 3)' array.json > /dev/null
hxstrive@localhost:~/test$ echo $?
4
  • -s 选项:将所有输入读入数组

# 正常输出
hxstrive@localhost:~/test$ jq '.' array.json array.json
[
  {
    "id": 1,
    "name": "Alice"
  },
  {
    "id": 2,
    "name": "Bob"
  }
]
[
  {
    "id": 1,
    "name": "Alice"
  },
  {
    "id": 2,
    "name": "Bob"
  }
]

# 使用-s选项
hxstrive@localhost:~/test$ jq -s '.' array.json array.json
[
  [
    {
      "id": 1,
      "name": "Alice"
    },
    {
      "id": 2,
      "name": "Bob"
    }
  ],
  [
    {
      "id": 1,
      "name": "Alice"
    },
    {
      "id": 2,
      "name": "Bob"
    }
  ]
]

注意,-s 选项会将两个文件内容合并为一个数组。

  • -r 选项:输出原始字符串,即不带引号的原始字符串

hxstrive@localhost:~/test$ jq -r '.[0].name' array.json
Alice
  • -R 选项:读取原始字符串而非 JSON

hxstrive@localhost:~/test$ echo "Hello" | jq -R '.'
"Hello"
  • -C 选项:为 JSON 着色

hxstrive@localhost:~/test$ jq -C '.' array.json
[
  {
    "id": 1,
    "name": "Alice"
  },
  {
    "id": 2,
    "name": "Bob"
  }
]

注意,在支持颜色的终端中,输出的 JSON 会有语法高亮

  • -M 选项:单色输出(默认)

hxstrive@localhost:~/test$ jq -M '.' array.json
[
  {
    "id": 1,
    "name": "Alice"
  },
  {
    "id": 2,
    "name": "Bob"
  }
]

强制禁用颜色,即使终端支持。

  • -S 选项:对对象的键进行排序

# 创建一个键无序的JSON对象
hxstrive@localhost:~/test$ echo '{"b": 2, "a": 1}' | jq -S '.'
{
  "a": 1,
  "b": 2
}

注意,输出的键按字母顺序排序。

  • --tab 选项:使用制表符缩进

hxstrive@localhost:~/test$ jq --tab '.' array.json
[
        {
                "id": 1,
                "name": "Alice"
        },
        {
                "id": 2,
                "name": "Bob"
        }
]

注意,输出使用制表符而非空格进行缩进。

  • --arg 选项:设置变量

hxstrive@localhost:~/test$ jq --arg name "Alice" '.[] | select(.name == $name)' array.json
{
  "id": 1,
  "name": "Alice"
}

注意,这里设置了变量 $name 为 "Alice"。

  • --argjson 选项:设置 JSON 变量

hxstrive@localhost:~/test$ jq --argjson id 1 '.[] | select(.id == $id)' array.json
{
  "id": 1,
  "name": "Alice"
}

输出 id 为 1 的对象。

  • --slurpfile 选项:从文件读取 JSON 数组,将 array.json 内容读入 $data 变量

hxstrive@localhost:~/test$ jq --slurpfile data array.json '$data' -n null
[
  [
    {
      "id": 1,
      "name": "Alice"
    },
    {
      "id": 2,
      "name": "Bob"
    }
  ]
]

注意,当使用 --slurpfile 加载外部文件到变量后,需要一个基础输入上下文才能执行过滤器。如果不指定输入源,jq 会默认等待从标准输入读取数据,导致光标一直闪烁等待输入。此时,使用 -n 选项可以提供 null 作为基础输入,让过滤器能够正常执行并输出变量内容。

  • --rawfile 选项:从文件读取原始字符串

hxstrive@localhost:~/test$ jq --rawfile content array.json '$content' -n null
"[\n  {\n    \"id\": 1,\n    \"name\": \"Alice\"\n  },\n  {\n    \"id\": 2,\n    \"name\": \"Bob\"\n  }\n]\n"

将 array.json 内容作为原始字符串读入 $content 变量。

  • --args 选项:将剩余参数视为字符串

hxstrive@localhost:~/test$ jq '.[] | select(.name == $ARGS.positional[0])' array.json --args Alice
{
  "id": 1,
  "name": "Alice"
}

使用 --args 传递 "Alice" 作为查询参数

  • --jsonargs 选项:将剩余参数视为 JSON

hxstrive@localhost:~/test$ jq '.[] | select(.id == $ARGS.positional[0])' array.json --jsonargs 1
{
  "id": 1,
  "name": "Alice"
}

使用 --jsonargs 传递数字 1 作为查询参数。

注意,jq 命令还有很多其他强大的功能,读者可以自行尝试。

 

青年最主要的任务是学习。 —— 朱德
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号