tryingtolearn
tryingtolearn

Reputation: 2636

jq: print key and value for each entry in an object when you have multiple values

{
   "host1": [
       {"ip": "10.1.2.3"}, 
       {"ip": "10.2.3.4"}, 
       {"ip": "10.3.4.5"},
   ],
   "host2": [
       {"ip":"10.1.2.2"}, 
       {"ip":"10.4.5.6"},
   ],
   "host3": [
       {"ip":"10.1.18.1"}
   ]
}

I'm borrowing most of the structure from another question but changing it since now an entry can have multiple values.

I want the output of the jq to be

host1  10.1.2.3
host1  10.2.3.4
host1  10.3.4.5
host2  10.1.2.2
host2  10.4.5.6
host3  10.1.18.1

host1 and host2 and printed for each value.

My attempt was:

jq -r 'to_entries[] | [.key, .value[].ip] | @tsv' file.json 

but the output of that was

host1  10.1.2.3  10.2.3.4  10.3.4.5
host2  10.1.2.2  10.4.5.6
host3  10.1.18.1

But I want them on separate lines.

Thanks

Upvotes: 1

Views: 1020

Answers (1)

pmf
pmf

Reputation: 36033

Save the ips individually to a variable to reference it inside the array:

jq -r 'to_entries[] | .value[].ip as $ip | [.key, $ip] | @tsv'
host1   10.1.2.3
host1   10.2.3.4
host1   10.3.4.5
host2   10.1.2.2
host2   10.4.5.6
host3   10.1.18.1

Demo


Instead of to_entries you can also use keys_unsorted to get access to the keys:

jq -r 'keys_unsorted[] as $key | .[$key][] | [$key, .ip] | @tsv'
host1   10.1.2.3
host1   10.2.3.4
host1   10.3.4.5
host2   10.1.2.2
host2   10.4.5.6
host3   10.1.18.1

Demo

Upvotes: 1

Related Questions