龙空技术网

shell之jq工具使用入门

大梦初醒lf 202

前言:

现时兄弟们对“jq根据name获取对象”大约比较注意,我们都想要学习一些“jq根据name获取对象”的相关内容。那么小编同时在网上搜集了一些有关“jq根据name获取对象””的相关内容,希望兄弟们能喜欢,同学们快快来学习一下吧!

jq 命令

在shell命令和脚本对复杂数据类型支持不是特别友好,介绍一个shell脚本中处理json对象的工具jq

样例json字符串如下:

test_info='{"name":"zhangsan","age":18,"work_exp":[{"name":"teacher","months":14},{"name":"ops","months":20},{"name":"dev","months":4}]'

基本解析

[root@VM_16_6_centos ~]# echo $test_info |jq .{  "name": "zhangsan",  "age": 18,  "work_exp": [    {      "name": "teacher",      "months": 14    },    {      "name": "ops",      "months": 20    },    {      "name": "dev",      "months": 4    }  ]}
基本过滤
[root@VM_16_6_centos ~]# echo $test_info |jq .name"zhangsan"[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp'[  {    "name": "teacher",    "months": 14  },  {    "name": "ops",    "months": 20  },  {    "name": "dev",    "months": 4  }][root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[2]'{  "name": "dev",  "months": 4}[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0:2]'[  {    "name": "teacher",    "months": 14  },  {    "name": "ops",    "months": 20  }][root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[-1]'{  "name": "dev",  "months": 4}[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[-1].name'"dev"[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp | .[1]'{  "name": "ops",  "months": 20}
构造对象
[root@VM_16_6_centos ~]# echo $test_info |jq '"teacher" as $first_job | {"first_job":$first_job,"second_job": .work_exp[1].name }'{  "first_job": "teacher",  "second_job": "ops"}[root@VM_16_6_centos ~]# echo $test_info |jq '"teacher" as $first_job | {"jobs": (.work_exp + .work_exp) }'{  "jobs": [    {      "name": "teacher",      "months": 14    },    {      "name": "ops",      "months": 20    },    {      "name": "dev",      "months": 4    },    {      "name": "teacher",      "months": 14    },    {      "name": "ops",      "months": 20    },    {      "name": "dev",      "months": 4    }  ]}[root@VM_16_6_centos ~]# echo $test_info |jq '"teacher" as $first_job | {"jobs": (.work_exp - .work_exp) }'{  "jobs": []}
内置运算
[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp |length '3[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0] | has("name") 'true[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0] | has("name1") 'false[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0] | keys '[  "months",  "name"][root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0].name | startswith("te") 'true[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp[0].name | endswith("er") 'true[root@VM_16_6_centos ~]# echo $test_info |jq '.work_exp | map(.months + 1) '[  15,  21,  5][root@VM_16_6_centos ~]# echo $test_info |jq '{"a":1,"b":2,"c":3} |map(.+1) '[  2,  3,  4][root@VM_16_6_centos ~]# echo $test_info |jq '{"a":1,"b":2,"c":3} |map_values(.+1) '{  "a": 2,  "b": 3,  "c": 4}

标签: #jq根据name获取对象