jq - Find a JSON object based on one of its values and get another value from it
jq - Find a JSON object based on one of its values and get another value from it
I've started using jq just very recently and I would like to know if something like this is even possible.
Example:
{
"address": [
{
"address": "10.1.2.3",
"interface": "wlan1_wifi"
},
{
"address": "10.1.2.4",
"interface": "ether1"
}
],
"wireless": [
{
"name": "wlan1_wifi"
}
]
}
Firstly let's transform the example json to this json object:
cat json | jq '. | {"wireless":[."wireless" | {"name": ."name"}]}'
{
"wireless": [
{
"name": "wlan1_wifi"
}
]
}
Now there's a problem. I need to assign an address to the "wireless"
array. The address is stored in "address"
array.
"wireless"
"address"
So the question: is there a way of finding the right json object in "address"
based on "name"
(in wireless array) and "interface"
(in address array) for every json object in "wireless"
array and then assigning "address"
to it?
"address"
"name"
interface"
"wireless"
"address"
The final result should look like this:
{
"wireless": [
{
"name": "wlan1_wifi",
"address": "10.1.2.3"
}
]
}
Josef - Yes, it’s possible, but see Minimal, Complete, and Verifiable example.
– peak
4 hours ago
sorry @hek2mgl, now it should be alright
– Josef Miegl
55 mins ago
1 Answer
1
The following produces the output as requested:
(.wireless.name) as $name
| .address
| select(.interface == $name)
| { wireless: {name: $name, address}}
However the above filter could potentially produce more than one result, so you might want to made modifications accordingly.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please take the time to create a mininal example instead of dropping a bunch of real world data into the question
– hek2mgl
4 hours ago