英文:
Parsing Array within Array: Unwanted cartesian-product behavior
问题
使用 jq
,我正在尝试解析一个包含嵌套数组的值数组。我的尝试创建了所有可能值的笛卡尔积,而不是解析嵌套数组中的特定属性。
jq '.[] | {id, versions: (.versions[] | {id}) }'
期望输出
[{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": [{
"id": "07e34a2d-be28-4925-afdd-79ddcbe54db9"
},
{
"id": "0e4ea89c-49da-4f79-a6bc-eec0dad19133"
}]
},
{
"id": "3644e592-c9c3-4c3b-b6d4-e6a7dbdf80fb",
"versions": [
{
"id": "9d63e112-7c42-43fa-b460-3f4389b691b3"
}]
}]
实际输出:笛卡尔积行为
{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": {
"id": "07e34a2d-be28-4925-afdd-79ddcbe54db9"
}
}
{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": {
"id": "0e4ea89c-49da-4f79-a6bc-eec0dad19133"
}
}
{
"id": "3644e592-c9c3-4c3b-b6d4-e6a7dbdf80fb",
"versions": {
"id": "9d63e112-7c42-43fa-b460-3f4389b691b3"
}
}
英文:
Using jq
, I am trying to parse an array of values, each with a nested array.
My attempt has created a cartesian product of all possible values instead of parsing specific properties within the nested array.
jq '.[] | {id, versions: (.versions[] | {id}) }'
Source
[{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
***,
"versions": [{
"id": "07e34a2d-be28-4925-afdd-79ddcbe54db9",
***
},
{
"id": "0e4ea89c-49da-4f79-a6bc-eec0dad19133",
***
}],
***
},
{
"id": "3644e592-c9c3-4c3b-b6d4-e6a7dbdf80fb",
***,
"versions": [{
"id": "9d63e112-7c42-43fa-b460-3f4389b691b3",
***
}],
***
}]
Expecting
[{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": [{
"id": "07e34a2d-be28-4925-afdd-79ddcbe54db9"
},
{
"id": "0e4ea89c-49da-4f79-a6bc-eec0dad19133"
}]
},
{
"id": "3644e592-c9c3-4c3b-b6d4-e6a7dbdf80fb",
"versions": [
{
"id": "9d63e112-7c42-43fa-b460-3f4389b691b3"
}]
}]
Actual: cartesian-product behavior
{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": {
"id": "07e34a2d-be28-4925-afdd-79ddcbe54db9"
}
}
{
"id": "afe45456-18fd-4523-a0ee-b7ed9d0a308e",
"versions": {
"id": "0e4ea89c-49da-4f79-a6bc-eec0dad19133"
}
}
{
"id": "3644e592-c9c3-4c3b-b6d4-e6a7dbdf80fb",
"versions": {
"id": "9d63e112-7c42-43fa-b460-3f4389b691b3"
}
}
答案1
得分: 2
jq 'map({id, versions: (.versions | map({id})) })'
英文:
If you want to get arrays, not a stream of items (in both, the inner and the outer case), don't destructure the source array with .[]
, use map
instead which retains the surrounding array:
jq 'map({id, versions: (.versions | map({id})) })'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论