Search code examples
jsontransformjolt

JOLT Transform accept element or array of elements


The API that I'm using is returning an array of elements or a single element, see INPUT_1 and INPUT_2. I need a spec that could handle both inputs and return the same output, see below examples.

Is this something possible? Am I asking too much?

I have input 1 :

{
  "rating": [
    {
      "primary-value": 3,
      "id": 1
    },
    {
      "quality-value": 3,
      "id": 2
    }
  ]
}

spec:

[
  {
    "operation": "shift",
    "spec": {
      "rating": {
        "*": {
          "*": "out[&1].fields.&"
        }
      }
    }
  }
]

output 1 :

{
  "out": [
    {
      "fields": {
        "primary-value": 3,
        "id": 1
      }
    },
    {
      "fields": {
        "quality-value": 3,
        "id": 2
      }
    }
  ]
}

If I have: input 2 :

{
  "rating": {
    "primary-value": 3,
    "id": 1
  }
}

spec 2:

[
  {
    "operation": "shift",
    "spec": {
      "rating": {
        "*": "out[0].fields.&"
      }
    }
  }
]

Desired output 2:

{
  "out": [
    {
      "fields": {
        "primary-value": 3,
        "id": 1
      }
    }
  ]
}

Solution

  • You can manage it by applying toList function within a modify spec before using shift spec such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": "=toList"
        }
      },
      { // nests the inputs of type input_2
        // while it doesn't have any impact for the inputs of type input_2
        "operation": "shift",
        "spec": {
          "rating": {
            "*": {
              "*": "out[&1].fields.&"
            }
          }
        }
      }
    ]