Search code examples
jolt

Transform if the json has a single object to array in JOLT


I have a Json which can have a inner json as an object or array, but i want to transform it as array always even if it has one element.

Input Json:

{
"payload": {
    "payloadVersion": "1",
    "settings": [
        {
            "image": "abc",
            "accounts": {
                "accountName": "netflix"
            }
        },
        {
            "image": "abc",
            "accounts": [
                {
                    "accountName": "amazon"
                },
                {
                    "accountName": "disney"
                }
            ]
        }
    ]
}
}

In the above accounts can be a single value or array, but I want it to be always as a array if it comes as single object and if it come as a array then it should be as is.

Output Json:

{
"payload": {
    "payloadVersion": "1",
    "settings": [
        {
            "image": "abc",
            "accounts": [
                {
                    "accountName": "netflix"
                }
            ]
        },
        {
            "image": "abc",
            "accounts": [
                {
                    "accountName": "amazon"
                },
                {
                    "accountName": "disney"
                }
            ]
        }
    ]
}
}

need help to write a JOLT specification for this


Solution

  • You can try the following spec:

    [
      {
        "operation": "shift",
        "spec": {
          "payload": {
            "*": "&1.&",
            "settings": {
              "*": {
                "*": "&3.&2.[&1].&",
                "accounts": {
                  "accountName": {
                    "@(2,accounts)": "&5.&4.[&3].&2[]"
                  },
                  "0": {
                    "@(2,accounts)": "&5.&4.[&3].&2"
                  }
                }
              }
            }
          }
        }
      }
    ]
    

    Hope that helps