jq常用操作

作者: Surpassme | 来源:发表于2022-07-26 23:06 被阅读0次

    1.简介

        jq 是一款非常强大的 JSON 命令行处理工具。其官网地址为:https://stedolan.github.io/jq/

    2.安装

        以CentOS为例:

    1.在线安装

    yum install -y epel-release && yum install -y jq
    

    2.离线安装

    • 访问官网,并下载jq(Linux 64-bit)
    • 在Linux中执行命令
    mv -f /home/surpass/jq-linux64 /usr/bin/jq
    

    3.验证安装

    # jq -h
    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;
    

    3.常用参数

    • -h/--help

    输出jq帮助信息

    • -V/--version

    输出jq版本信息

    • -c/--compact-output

    将每个JSON对象在单行内以紧凑的形式输出

    • -n/--null-input

    不读取任何输入,将null做为输入运行一次

    • -r/--raw-output

    在开启这个选项的情况下,如果 过滤器 的结果是 string,就会直接写入标准输出而不是以 JSON string 的格式输出。这在 jq 过滤器和其他处理 非-JSON 系统交互时比较有用。

    • -R/--raw-input

    不要将输入解析为JSON。相反,每行文本都以字符串形式传递给过滤器

    • -C/--color-output和-M/--monochrome-output

    默认情况下,如果是写入到终端,jq 会输出 colored JSON 。也可以使用 -C 强制输出彩色的JSON 到管道或者文件。也可以使用 -M 禁掉输出 colored JSON 。

    • -S/--sort-keys

    将每个 JSON object 的各个字段按照 key 排序的顺序输出

    • --tab

    使用tab符做为缩进符

    • --indent n

    指定缩进使用的空格数,范围为[-1,7]

    4.基本过滤器

        在使用过滤器前,先来看看一个示例数据,如下所示:

    {
      "personInfo": {
        "name": "Surpass",
        "age": 28,
        "location": "shanghai"
      },
      "others": [
        "a",
        "b",
        "c"
      ]
    }
    
    • 1、.

        最简单也是最平常的过滤器,其作用是接收输入并原样输出的过滤器

    cat test.json | jq .
    {
      "personInfo": {
        "name": "Surpass",
        "age": 28,
        "location": "shanghai"
      },
      "others": [
        "a",
        "b",
        "c"
      ]
    }
    
    • 2、.key.key.key'.["key"]'

        获取指定key的值,如果没有找到指定的key,则输出null

    # cat test.json | jq .personInfo
    {
      "name": "Surpass",
      "age": 28,
      "location": "shanghai"
    }
    
    # cat test.json | jq .personInfo.name
    "Surpass"
    
    # cat test.json | jq '.["personInfo"]'
    {
      "name": "Surpass",
      "age": 28,
      "location": "shanghai"
    }
    # cat test.json | jq .abc
    null
    
    • 3、.key?

        使用 .key 时,当 . 不是一个数组或对象时会而报错,使用 .key? 则不会报错

    # echo "1" | jq .a
    jq: error (at <stdin>:1): Cannot index number with string "a"
    # echo "1" | jq .a?
    # 
    
    • 4、.[index].[startIndex:endIndex]

        获取对象或value为数组或字符串的子数组或子符串。索引主要有以下几种形式

    • 索引下标从0开始,
    • 支持负索引,-1表示最后一个元素,-2表示倒数第二个元素
    # cat test.json | jq .others[0]
    "a"
    # cat test.json | jq .others[1:3]
    [
      "b",
      "c"
    ]
    # cat test.json | jq .others[-3:-1]
    [
      "a",
      "b"
    ]
    # cat test.json | jq .others[:3]
    [
      "a",
      "b",
      "c"
    ]
    # echo '[{"name":"Surpass","age":28},{"oters":1234}]' | jq .[0]
    {
      "name": "Surpass",
      "age": 28
    }
    # echo '["Surpass"]' | jq .[0][0:3]
    "Sur"
    
    • 5、.[]

        获取所有的value值

    # cat test.json | jq .[]
    {
      "name": "Surpass",
      "age": 28,
      "location": "shanghai"
    }
    [
      "a",
      "b",
      "c"
    ]
    
    • 6、keys

        获取所有的key对象

    # cat test.json | jq keys
    [
      "others",
      "personInfo"
    ]
    
    • 7、[.[]]

        获取所有value组成的数组

    cat test.json | jq [.[]]
    [
      {
        "name": "Surpass",
        "age": 28,
        "location": "shanghai"
      },
      [
        "a",
        "b",
        "c"
      ]
    ]
    
    
    • 8、.[].key

        获取数组元素中指定key的所有值

    # echo '[{"name":"Surpass"},{"name":"Kevin"},{"name":"Tina"}]' | jq .[].name
    "Surpass"
    "Kevin"
    "Tina"
    

    如果需要将输出结果再次组装为数组,可以这样使用 [.[].key]

    • 9、,

        使用多个筛选条件

    # cat test.json | jq .personInfo | jq [.name,.age]
    [
      "Surpass",
      28
    ]
    
    • 10、管道

        可以通过 | 实现管道功能,从而达到对处理的结果进行二次或多次处理

    # cat test.json | jq '.personInfo|.name,.age'
    "Surpass"
    28
    # cat test.json | jq '.others|.[2]'
    "c"
    

    也可以使用Linux自带的 | 实现同样的功能。

    • 11、length

        length 可以获取字符串或数组的长度

    # cat test.json | jq '.others|length'
    3
    # cat test.json | jq '.personInfo|length'
    3
    # cat test.json | jq '.personInfo|.name|length'
    7
    
    • 12、map

        可以实现对数组的每一项操作,然后进行合并结果。

    # echo '["Surpass","Kevin","Tina"]' | jq 'map(length)'
    [
      7,
      5,
      4
    ]
    
    • 13、filter(select)

        可以实现对输入项进行判断,然后仅返回符合条件的项

    # echo '["Surpass","Kevin","Tina"]' | jq 'map(select(.|length>5))'
    [
      "Surpass"
    ]
    # echo '["Surpass","Kevin","Tina"]' | jq 'map(select(.|length>=5))'
    [
      "Surpass",
      "Kevin"
    ]
    
    • 14、\()

        可以实现字符串插值功能

    # cat test.json | jq '"Hello \(.personInfo|.name)"'
    "Hello Surpass"
    # echo '{"name":"Surpass","age":28}' | jq '"age is: \(.age)"'
    "age is: 28"
    
    • 15、+

        可以实现字符串拼接功能

    # echo '{"name":"Surpass","age":28}' | jq '"name is :" + .name'
    "name is :Surpass"
    cat test.json | jq '"name is :" + .personInfo.name '
    "name is :Surpass"
    
    • 16、if/elif/else

        可以使用 if .. then .. elif .. then .. else .. end 实现条件判断

    # echo '[0, 1, 2, 3]' \
    > | jq 'map(if . == 0 then "zero" elif . == 1 then "one" elif . == 2 then "two" else "many" end)'
    [
      "zero",
      "one",
      "two",
      "many"
    ]
    
    • 17、构造 object 或数组

        可以通过 {} 和 [] 构造新的 object 或 数组

    • object:
    # echo '["Surpass","Kevin","Tina"]' | jq '{name:.[0]}'
    {
      "name": "Surpass"
    }
    
    # echo '{"name":"Surpass","ages":[28,29,30]}' | jq '{name,age: .ages[]}'
    {
      "name": "Surpass",
      "age": 28
    }
    {
      "name": "Surpass",
      "age": 29
    }
    {
      "name": "Surpass",
      "age": 30
    }
    
    • array
    # echo '{"name":"Surpass","age":28,"location":"Shanghai"}' | jq '[.name,.age,.location]'
    [
      "Surpass",
      28,
      "Shanghai"
    ]
    
    • 18、join

        可以进行数组拼接功能。

    # echo '["Surpass","28","Shanghai"]' | jq '.|join("--")'
    "Surpass--28--Shanghai"
    
    • 19、split

        可对字符串进行拆分

    # echo '"Surpass--28--Shanghai"' | jq 'split("--")'
    [
      "Surpass",
      "28",
      "Shanghai"
    ]
    

    相关文章

      网友评论

        本文标题:jq常用操作

        本文链接:https://www.haomeiwen.com/subject/jpeairtx.html