0
votes

I need to convert a json array that has objects with a child array into an array of objects with one record (object) per each child array object.

Input:

[
  {
    "recId": 1,
    "Attrs": [
      {
        "color": "red",
        "priority": 1
      },
      {
        "color": "purple",
        "priority": 2
      }
    ]
  },
  {
    "recId": 2,
    "Attrs": [
      {
        "color": "gold",
        "priority": 3
      },
      {
        "color": "blue",
        "priority": 2
      }
    ]
  },
  {
    "recId": 3,
    "Attrs": null
  }
]

Desired Output:

[
  {
    "recId": 1,
    "color": "red",
    "priority": 1
  },
  {
    "recId": 1,
    "color": "purple",
    "priority": 2
  },
  {
    "recId": 2,
    "color": "gold",
    "priority": 3
  },
  {
    "recId": 2,
    "color": "blue",
    "priority": 2
  }
]

I've tried several different things without success. I can't find any good examples anywhere or documentation. I cannot figure out how to capture the recId and have each object of the Attrs be a separate record.

1

1 Answers

1
votes

You could transform/iterate through every item on the Array using map. Then take each object in Attrs using another map and returning the same object plus the recId.

This will output an array of array so you need to flatten it (with the function flatten or using flatMap instead of the first map).

To ignore the null, you could use the writer property skipNullOn.

%dw 2.0
output application/json skipNullOn="everywhere"
---
flatten(payload map ((item, index) -> 
    item.Attrs map ((attr, index) -> 
        {"recId": item.recId} ++ attr
        )
    )
)