Home > Net >  jq - unnest/unwind object with array, i.e. make new object for every item in nested array
jq - unnest/unwind object with array, i.e. make new object for every item in nested array

Time:12-06

I am not sure if the operation name is proper here, but the example should show well my intention. This is exactly how unwind aggregation operation in Mongo or unnest in BigQuery behave.

Having that json structure:

[
  {
    "root-array-a": [
      11,
      12,
      13
    ],
    "root-property-b": 22,
    "root-property-c": 33
  }
]

I would like to get a result:

[
  {
    "root-property-a": 11,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 12,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 13,
    "root-property-b": 22,
    "root-property-c": 33
  },
]

CodePudding user response:

This works:

jq 'map({"root-property-a": .["root-array-a"][]}   . | del(.["root-array-a"]))'

{"root-property-a": .["root-array-a"][]} constructs an object with a root-property-a key for each value in root-array-a (because of the [] operator, and because jq implicitly fans out multiple outputs as necessary). . adds that key to the original object, and the del removes the unwanted array.

CodePudding user response:

You can use stream the array when constructing an object which will generate each combination of inputs:

map({
    "root-property-a": ."root-array-a"[],
    "root-property-b": ."root-property-b",
    "root-property-c": ."root-property-c"
})

Output:

[
  {
    "root-property-a": 11,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 12,
    "root-property-b": 22,
    "root-property-c": 33
  },
  {
    "root-property-a": 13,
    "root-property-b": 22,
    "root-property-c": 33
  }
]
  • Related