Search code examples
jqueryjsonbashjqjsonpath

Get value of parent element by child jq


Code:

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

I need to return the agentId value with the value userName. I know how to do it with JSONPath

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

, but don't know how with jq.


Solution

  • Assuming your input JSON is

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

    To get the agentId values from all items of the endpointAgents array where in the same object at least one object in the clients array has a userProfile.userName string value that contains a given substring, I'd go with

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

    Demo

    In order import the query string from outside jq, use the --arg parameter

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