Search code examples
jsontransactionsjolt

Jolt Transform an Array Objects and Move Some Fields to Nested Array


I want to transform the following array of diagnoses and move all the fields except sequence to a nested coding array.

JSON Input

{
  "diagnoses": [
    {
      "version": "20230607",
      "code": "A100",
      "display": "Diagnosis 1",
      "sequence": 1
    },
    {
      "version": "20230607",
      "code": "B100",
      "display": "Diagnosis 2",
      "sequence": 2
    }
  ]
}

Desired Output

{
  "diagnoses": [
    {
      "coding": [
        {
          "version": "20230607",
          "code": "A100",
          "display": "Diagnosis 1"
        }
      ],
      "sequence": 1
    },
    {
      "coding": [
        {
          "version": "20230607",
          "code": "B100",
          "display": "Diagnosis 2"
        }
      ],
      "sequence": 2
    }
  ]
}

I can transform a single diagnoses object as expected but can't correctly transpose the array. Here's an example of the input and spec for transforming a single diagnoses object.

JSON Input (single object)

{
  "version": "20230607",
  "code": "A100",
  "display": "Diagnosis 1",
  "sequence": 1
}

Jolt Spec

[
  {
    "operation": "shift",
    "spec": {
      "sequence": "&",
      "*": "coding[0].&"
    }
  }
]

Solution

  • Ignore that you have 2 different types of input and write your own Jolt spec. Because you have your array input in the sequence key, or otherwise you have them in the root object.

    [
      {
        "operation": "shift",
        "spec": {
          "diagnoses": {
            "*": {
              "*": "&2[&1].coding[0].&",
              "sequence": "&2[&1].&"
            }
          },
          "*": "coding[0].&",
          "sequence": "&"
        }
      }
    ]