jsonjolt

JoltTransform: Split each object of input array into 2 separate object and place it in output array


I am using Jolt Transform to convert my input JSON.

Input JSON:

[
  {
    "saleQty": 7,
    "returnQty": 8
  }
]

Jolt Spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "saleQty": {
          "*": {
            "@1": "[#3].qty",
            "#SALE": "[#3].type"
          }
        },
        "returnQty": {
          "*": {
            "@1": "[#3].qty",
            "#RETURN": "[#3].type"
          }
        }
      }
    }
  },
  {
    "operation": "remove",
    "spec": {
      "*": {
        "saleQty": {
          "0": ""
        },
        "returnQty": {
          "0": ""
        }
      }
    }
  }
]

Actual output is matching my expected result:

[
  {
    "qty": 7,
    "type": "SALE"
  },
  {
    "qty": 8,
    "type": "RETURN"
  }
]

My problem is, when I try to give more than 1 objects in my JSON array, the same jolt spec is not able to create new objects in my output JSON array. Example,

Input JSON:

[
  {
    "saleQty": 7,
    "returnQty": 8
  },
  {
    "saleQty": 14,
    "returnQty": 19
  }
]

Output JSON after transform:

[
  {
    "qty": [
      7,
      14
    ],
    "type": [
      "SALE",
      "SALE"
    ]
  },
  {
    "qty": [
      8,
      19
    ],
    "type": [
      "RETURN",
      "RETURN"
    ]
  }
]

Expected output JSON:

[
  {
    "qty": 7,
    "type": "SALE"
  },
  {
    "qty": 8,
    "type": "RETURN"
  },
  {
    "qty": 14,
    "type": "SALE"
  },
  {
    "qty": 19,
    "type": "RETURN"
  }
]

Can somebody please help me in correcting my Jolt Spec. I am not sure why it is creating list of "qty" and "type" in my output.

Tried to convert my input JSON into expected output JSON tree using Jolt Transform, but the Jolt spec I had written is not returning me the expected output.


Solution

  • You can use the following transformation :

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*Qty": {
              "@": "&2_&(1,1).qty", // separate the layers by &2_&(1,1) : 
              //&2 stands for the uppermost index
              //&(1,1) represents going 1 level up the tree and grabbing the first replacement of asterisk
              "$(0,1)": "&2_&(1,1).type" // bring the key represented by 1st asterisk
                //indeed there's already only one asterisk
            }
          }
        }
      },
      { //get rid of the keys of the objects
        "operation": "shift",
        "spec": {
          "*": "[]"
        }
      },
      { //convert expressions uppercase 
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "*": "=toUpper"
          }
        }
      }
    ]
    

    the demo on the site https://jolt-demo.appspot.com/ is :

    enter image description here