Home > Software design >  Grouping JSON elements using Jolt transform
Grouping JSON elements using Jolt transform

Time:02-03

I need help in jolt transform spec. Below is my work till now.

Input:

[
  {
    "ID": "1234",
    "Date": "2020-12-10",
    "Time": "06:00:00",
    "Rate": null,
    "Interest": null,
    "Term": 99
  },
  {
    "ID": "1234",
    "Date": "2020-12-11",
    "Time": "07:00:00",
    "Rate": 8,
    "Interest": null,
    "Term": 99
  }
]

Jolt Code used:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "ID": "@(1,ID).id",
        "Date": "@(1,ID).date",
        "Time": "@(1,ID).group.time",
        "Rate": "@(1,ID).group.rate",
        "Interest": "@(1,ID).group.interest",
        "Term": "@(1,ID).group.term"
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "id": "ONE"
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]

Current output:

[
  {
    "id": "1234",
    "date": ["2020-12-10", "2020-12-11"],
    "group": {
        "time": ["06:00:00", "07:00:00"],
        "rate": 8,
        "interest": null,
        "term": [99, 99]
    }
 }
]

Expected output

[
  {
    "id": "1234",
    "date": "2020-12-10",
    "group": {
      "time": "06:00:00",
      "rate": null,
      "interest": null,
      "term": 99
    }
  },
  {
    "id": "1234",
    "date": "2020-12-11",
    "group": {
      "time": "07:00:00",
      "rate": 8,
      "interest": null,
      "term": 99
    }
  }
]

When using only single json object, this code works fine. But when we use multiple items with same id, it starts grouping all related fields.

CodePudding user response:

You can use square bracketed notation([&1]) as the common factor while qualifying rest of the elements other than id and Date as group such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "ID": "[&1].&",
        "Date": "[&1].&",
        "*": "[&1].group.&"
      }
    }
  }
]

enter image description here

  •  Tags:  
  • Related