Goddy
Goddy

Reputation: 44

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

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
  },
]

Upvotes: 0

Views: 148

Answers (2)

hobbs
hobbs

Reputation: 240472

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.

Upvotes: 1

knittl
knittl

Reputation: 265668

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
  }
]

Upvotes: 1

Related Questions