abb
abb

Reputation: 382

Unable to transform a JSON Object into Array of objects using JOLT JSON library

Input JSON that I have to transform is as follows :

{
  "Business": [
    {
      "Label": "Entertainment",
      "category": "Advert",
      "weight": "",
      "types": [
        "T1",
        "T2"
      ]
    },
    {
      "Label": "FMCG",
      "category": "Campaign",
      "weight": "",
      "types": [
        "T9",
        "T10"
      ]
    }
  ]
}

Expected Output :

{
  "Business": [
    {
      "Label": "Entertainment",
      "category": "Advert",
      "weight": "",
      "types": "T1"
    },
    {
      "Label": "Entertainment",
      "category": "Advert",
      "weight": "",
      "types": "T2"
    },
    {
      "Label": "FMCG",
      "category": "Campaign",
      "weight": "",
      "types": "T9"
    },
    {
      "Label": "FMCG",
      "category": "Campaign",
      "weight": "",
      "types": "T10"
    }
  ]
}

I have tried the different JsonSpecs provided at the JOLT github help page. But I am not able to solve this. Any help or pointers will be appreciated.

Upvotes: 2

Views: 3697

Answers (1)

Milo S
Milo S

Reputation: 4586

You have to do two shift operations.

You want to "duplicate" the Label and Category based on how many entries you have in "types" array. So do that first, into a temporary "bizArray".

Also record which "type" goes with that duplicated Label and Category in a temporary "typeArray", that has the same indexes as the bizArray.

In the second shift, "join" the two parallel arrays, "bizArray" and "typesArray" to get your final array.

Spec

[
  {
    "operation": "shift",
    "spec": {
      "Business": {
        "*": { // business array
          "types": {
            "*": { // type array
              "@2": "bizArray[]",  // make a copy of the whole biz object
              "@": "typesArray[]"
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "bizArray": {
        "*": { // bizArray index
          "Label": "Business[&1].Label",
          "category": "Business[&1].category",
          "weight": "Business[&1].weight"
        }
      },
      "typesArray": {
        "*": "Business[&].types"
      }
    }
  }
]

Upvotes: 8

Related Questions