仅 JQ return 将子结果与父结果匹配
JQ only return matching child results with parent
我正在尝试获取存在子键匹配的 JSON 数据,但我想从其他不匹配的子元素中排除数据。一个示例将使用以下 JSON,尝试从父项 return id
和子项 quantity
,其中子项 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"
}
]
}
]
我正在寻找的输出是:
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]
当我根据对象 ID 使用 select
时,它也 return 是其他 ID 的值。我确定对此有一个简单的答案,但我一直无法弄清楚。
jq '.[] | select ( .line_items[].catalog_object_id == "VJXWCBDL" ) | [ .id, .line_items[].quantity ]' test.json
我应该怎么做?
尝试
jq --arg q "VJXWCBDL" '
.[] | [.id] + (.line_items[] | select(.catalog_object_id == $q) | [.quantity])
' test.json
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]
我正在尝试获取存在子键匹配的 JSON 数据,但我想从其他不匹配的子元素中排除数据。一个示例将使用以下 JSON,尝试从父项 return id
和子项 quantity
,其中子项 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"
}
]
}
]
我正在寻找的输出是:
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]
当我根据对象 ID 使用 select
时,它也 return 是其他 ID 的值。我确定对此有一个简单的答案,但我一直无法弄清楚。
jq '.[] | select ( .line_items[].catalog_object_id == "VJXWCBDL" ) | [ .id, .line_items[].quantity ]' test.json
我应该怎么做?
尝试
jq --arg q "VJXWCBDL" '
.[] | [.id] + (.line_items[] | select(.catalog_object_id == $q) | [.quantity])
' test.json
[
"a",
"1"
]
[
"c",
"2"
]
[
"d",
"4"
]