专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 通过jq获取父元素值的例子

通过jq获取父元素值的例子

更新时间:2022-09-19 10:24:16 来源:星辉 浏览813次

如何通过jq获取父元素值?星辉小编来给大家举例说明。

代码:

{ 
"endpointAgents":[ 
{
      "agentId": "MyId",
      "agentName": "MYNAME",
      "location": {
        "locationName": "location"
      },
      "clients": [
        {
          "userProfile": {
            "userName": "Name"
          },
          "browserExtensions": [
            {
              "active": false
            }
          ]
        },
      ],
      "totalMemory": "16222 MB",
      "agentType": "enterprise"
    }

需要返回值为userName的agentId值。知道如何使用 JSONPath,但不知道jq如何。

($.endpointAgents[?(@.clients.userName=~ 'a')].agentId)

假设输入 JSON 是

{
  "endpointAgents": [
    {
      "agentId": "MyId",
      "agentName": "MYNAME",
      "location": {
        "locationName": "location"
      },
      "clients": [
        {
          "userProfile": {
            "userName": "Name"
          },
          "browserExtensions": [
            {
              "active": false
            }
          ]
        }
      ],
      "totalMemory": "16222 MB",
      "agentType": "enterprise"
    }
  ]
}

要从数组的所有项中获取agentId值,其中在同一个对象中,数组中至少有一个对象具有包含给定子字符串的字符串值,可以选择endpointAgentsclientsuserProfile.userName

jq -r '
  .endpointAgents[]
  | select(.clients | map(.userProfile.userName | contains("a")) | any)
  | .agentId
'
MyId

为了从 jq 外部导入查询字符串,请使用--arg参数

jq -r --arg query "a" ' … contains($query) … '

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>