Reputation: 1361
I have input JSON data in a bunch of files, with an IP address as one of the keys. I need to iterate over a the files, and I need to get "stuff" out of them. The IP address is different for each file, but I'd like to use a single jq command to get the data. I have tried a bunch of things, the closest I've come is this:
jq '.facts | keys | keys as $ip | .[0]' a_file
On my input in a_file of:
{
"facts": {
"1.1.1.1": {
"stuff":"value"
}
}
}
it returns the IP address, i.e. 1.1.1.1
, but then how do I to go back do something like this (which is obviously wrong, but I hope you get the idea):
jq '.facts.$ip[0].stuff' a_file
In my mind I'm trying to populate a variable, and then use the value of that variable to rewind the input and scan it again.
=== EDIT === Note that my input was actually more like this:
{
"facts": {
"1.1.1.1": {
"stuff": {
"thing1":"value1"
}
},
"outer_thing": "outer_value"
}
}
So I got an error:
jq: error (at <stdin>:9): Cannot index string with string "stuff"
This fixed it- the question mark after .stuff
:
.facts | keys_unsorted[] as $k | .[$k].stuff?
Upvotes: 0
Views: 1505
Reputation: 85550
You almost got it right, but need the object value iterator construct, .[]
to get the value corresponding to the key
.facts | keys_unsorted[] as $k | .[$k].stuff
This assumes that, inside facts
you have one object containing the IP address as the key and you want to extract .stuff
from it.
Optionally, to guard against objects that don't contain stuff
inside, you could add ?
as .[$k].stuff?
. And also you could optionally validate keys against a valid IP regex condition and filter values only for those keys.
Upvotes: 1