Jq print key and value for all in sub-object

jqjson

I found this Q/A with the solution to print all the keys in an object:

jq -r 'keys[] as $k | "\($k), \(.[$k] | .ip)"' 

In my case I want to perform the above but on a sub-object:

jq -r '.connections keys[] as $k | "\($k), \(.[$k] | .ip)"'

What is the proper syntax to do this?

Best Answer

Simply pipe to keys function:

Sample input.json:

{
    "connections": {
        "host1": { "ip": "10.1.2.3" },
        "host2": { "ip": "10.1.2.2" },
        "host3": { "ip": "10.1.18.1" }
    }
}

jq -r '.connections | keys[] as $k | "\($k), \(.[$k] | .ip)"' input.json

The output:

host1, 10.1.2.3
host2, 10.1.2.2
host3, 10.1.18.1
Related Question