Reputation: 45
For the following json file I need to get 'name' element based on search results for that specific entry
eg: json.txt
{
"regions": {
"var1": {
"name": "City 1",
"domains": {
"var3": {
"Owner": "Joe"
}
}
},
"var2": {
"name": "City 2",
"domains": {
"var4": {
"Owner": "Brown"
}
}
}
}
}
I tried
$ jq --arg arg1 'var4' '.regions | if (to_entries[].value.domains[$arg1]) then to_entries[].value.name else empty end' json.txt
but that returns
"City 1"
"City 2"
I want the result to only fetch
"City 2"
Any assistance would be greatly appreciated
Upvotes: 3
Views: 356
Reputation: 116650
You need to pull to_entries[]
outside the if ... then ... else ... end
clause:
.regions | to_entries[] | if .value.domains[$arg1] then .value.name else empty end
This can be shortened to:
.regions | to_entries[] | .value | select(.domains[$arg1]) | .name
Upvotes: 2