hopeless-dream

导航

Linux 中 json 格式化工具 jq

安装

jq属于epel源,所以需要安装epel

[root@master kubernetes]# yum install -y epel-release

安装工具

[root@master kubernetes]# yum install -y jq

测试使用

测试数据

[root@master ~]# vim test
{ "name":"Tom", "age":18, "gender":"male", "phone":["110"], "speciality":null }
{ "name":"Jerry", "age":16, "gender":"female", "phone":null,"speciality":["eat","sleep"] }

使用方法

1、普通转换:相当于解析根节点 "."

[root@master ~]# jq < test
{
  "name": "Tom",
  "age": 18,
  "gender": "male",
  "phone": [
    "110"
  ],
  "speciality": null
}
{
  "name": "Jerry",
  "age": 16,
  "gender": "female",
  "phone": null,
  "speciality": [
    "eat",
    "sleep"
  ]
}

也可以写根节点

[root@master ~]# jq . < test
{
  "name": "Tom",
  "age": 18,
  "gender": "male",
  "phone": [
    "110"
  ],
  "speciality": null
}
{
  "name": "Jerry",
  "age": 16,
  "gender": "female",
  "phone": null,
  "speciality": [
    "eat",
    "sleep"
  ]
}

2、解析属性

[root@master ~]# jq .age < test
18
16

 

[root@master ~]# jq .name < test
"Tom"
"Jerry"

3、解析多个属性

[root@master ~]# jq '[.name,.age,.speciality]' < test
[
  "Tom",
  18,
  [
    "sleep",
    "read"
  ]
]
[
  "Jerry",
  16,
  [
    "eat",
    "sleep"
  ]
]

4、测试解析列表索引

修改测试数据

[root@master ~]# vim test
{ "name":"Tom", "age":18, "gender":"male", "phone":["110"], "speciality":["sleep","read"] }
{ "name":"Jerry", "age":16, "gender":"female", "phone":null, "speciality":["eat","sleep"] }

解析

[root@master ~]# jq '.speciality[0]' < test
"sleep"
"eat"

[root@master ~]# jq '.speciality[1]' < test
"read"
"sleep"

负索引解析

[root@master ~]# jq '.speciality[-1]' < test
"read"
"sleep"

 

5、使用制表符处理结果数据

[root@master ~]# jq '[.name,.age,.speciality[0]] | @tsv'  < test
"Tom\t18\tsleep"
"Jerry\t16\teat"

可以去除制表符

[root@master ~]# jq '[.name,.age,.speciality[0]] | @tsv'  < test|sed 's/\\t/,/g'
"Tom,18,sleep"
"Jerry,16,eat"

 

posted on 2022-05-26 15:29  hopeless-dream  阅读(398)  评论(0编辑  收藏  举报