skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
      }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search