shell命令jq用法详解

1、jq介绍

        jq是Linux系统中把文本字符串格式化成json格式的工具。

        jq命令用于将JSON数据转换为更易读的格式并将其打印到 Linux 上的标准输出。jq命令是围绕过滤器构建的,过滤器用于从JSON文件中仅查找和打印所需的数据。

        jq是一个轻量级的命令行JSON处理工具,用于解析、过滤、修改和操作JSON数据。它提供了一种简洁和灵活的方式来处理JSON数据,可以与其他命令行工具(如grep、sed)结合使用,以实现复杂的JSON处理任务。

2、jq安装

安装EPEL源(这一步可以省略):
yum install epel-release -y

安装完EPEL源后,可以查看下jq包是否存在
yum list jq

安装jq
yum install jq -y

3、json数据准备

[{
	"id": "1",
	"name": "zhangsan",
	"age": "18"
}, {
	"id": "2",
	"name": "lisi",
	"age": "19"
}, {
	"id": "3",
	"name": "wangwu",
	"age": "20"
}]

4、jq使用

4.1 jq --help

[root@dgw-machine ~]# 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.

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).

For more advanced filters see the jq(1) manpage ("man jq")
and/or 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;
  -e               set the exit status code based on the output;
  -s               read (slurp) all inputs into an array; apply filter to it;
  -r               output raw strings, not JSON texts;
  -R               read raw strings, not JSON texts;
  -C               colorize JSON;
  -M               monochrome (don't colorize JSON);
  -S               sort keys of objects on output;
  --tab            use tabs for indentation;
  --arg a v        set variable $a to value <v>;
  --argjson a v    set variable $a to JSON value <v>;
  --slurpfile a f  set variable $a to an array of JSON texts read from <f>;
  --rawfile a f    set variable $a to a string consisting of the contents of <f>;
  --args           remaining arguments are string arguments, not files;
  --jsonargs       remaining arguments are JSON arguments, not files;
  --               terminates argument processing;

Named arguments are also available as $ARGS.named[], while
positional arguments are available as $ARGS.positional[].

See the manpage for more options.

4.2 显示数据

jq '.' test.json

或者
cat test.json | jq '.'
cat test.json | jq -r '.'

4.3 访问和输出 JSON 文件中数组中存在的元素

jq '.[]' test.json

4.4 过滤数组

        可以使用方括号([])来过滤数组中的元素。例如,要选择数组中的第一个元素,可以使用以下命令:

jq '.[1]' test.json

4.5 访问属性

        使用点操作符(.)来选择JSON对象中的字段。例如,要选择名为"name"的字段,可以使用以下命令:

jq '.[1].name' test.json

4.6 过滤条件(if-then-else)

jq 'if .[].age > "19" then .[].name else empty end' test.json

4.7 过滤多个字段

        可以使用逗号(,)将多个字段组合在一起。例如,要选择名字和年龄字段,可以使用以下命令:

jq '.[].name, .[].age' test.json

4.8 过滤组合操作符(and/or)

        可以使用逻辑操作符(and/or)来组合多个过滤条件。例如,要选择年龄大于18岁并且名字以"J"开头的人,可以使用以下命令:

jq 'select(.age > 18 and .name | startswith("J"))' file.json

4.9 修改字段

        可以使用赋值操作符(=)来修改字段的值。例如,要将名字字段修改为"John",可以使用以下命令:

jq '.[1].name = "John"' test.json

4.10 过滤数组中的对象

        可以使用点操作符(.)和方括号([])来选择数组中的对象。例如,要选择数组中所有年龄大于19岁的人,可以使用以下命令:

jq '.[] | select(.age > "19")' test.json

4.11 过滤嵌套字段

        可以使用点操作符(.)来选择嵌套在对象中的字段。例如,要选择嵌套在"address"字段中的"city"字段,可以使用以下命令:

jq '.address.city' file.json

4.12 数组聚合操作

        可以使用reduce函数将数组中的元素聚合成一个值。例如,要计算数组中年龄的总和,可以使用以下命令:

jq 'reduce .[] as $item (0; . + $item.age)' file.json

4.13 数组映射操作

        可以使用map函数将数组中的元素进行映射转换。例如,要将数组中的所有年龄加1,可以使用以下命令

jq 'map(.age + 1)' file.json

4.14 数组排序

        可以使用sort_by函数对数组进行排序。例如,要按照年龄对数组中的对象进行升序排序,可以使用以下命令:

jq 'sort_by(.age)' file.json

4.15 数组切片

        可以使用切片操作符([start:end])来选择数组中的一部分元素。例如,要选择数组中的前3个元素,可以使用以下命令:

jq '.[:3]' file.json

4.16 变量和函数

        可以使用$符号定义变量,并使用def关键字定义函数。例如,要定义一个函数来计算人的BMI指数,可以使用以下命令:

jq 'def bmi: .weight / (.height * .height); .[] | .name, bmi' file.json

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/131493398