解析数组中的数组:不希望的笛卡尔积行为

huangapple go评论61阅读模式
英文:

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})) })'

Demo

huangapple
  • 本文由 发表于 2023年4月10日 19:37:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定