I am trying to get JSON data where a child key match exists, but I want to exclude data from other child elements that don't match. An example would use the following JSON, trying to return id
from the parent and quantity
from the child, where the child catalog_object_id
"VJXWCBDL":
[
{
"id": "a",
"line_items": [
{
"catalog_object_id": "IKF7HPIP",
"quantity": "5"
},
{
"catalog_object_id": "VJXWCBDL",
"quantity": "1"
}
]
},
{
"id": "b",
"line_items": [
{
"catalog_object_id": "JXOACUE",
"quantity": "4"
}
]
},
{
"id": "c",
"line_items": [
{
"catalog_object_id": "VJXWCBDL",
"quantity": "2"
},
{
"catalog_object_id": "RGQMKXKL",
"quantity": "3"
}
]
},
{
"id": "d",
"line_items": [
{
"catalog_object_id": "VJXWCBDL",
"quantity": "4"
}
]
}
]
The output that I'm looking for is:
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]
When I use select
based on the object id, it returns the values for the other ids as well. I'm sure there's an easy answer to this that I haven't been able to figure out.
jq '.[] | select ( .line_items[].catalog_object_id == "VJXWCBDL" ) | [ .id, .line_items[].quantity ]' test.json
What should I be doing instead?
CodePudding user response:
Try
jq --arg q "VJXWCBDL" '
.[] | [.id] (.line_items[] | select(.catalog_object_id == $q) | [.quantity])
' test.json
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]