Search code examples
javajsonspringjolt

How to "shift" only one element on array using index


My input JSON looks like:

{
  "id": "eea1c86e-e4e2-36df-a775-ad44a6d2d94e",
  "d": {
    "flag": 0,
    "a0": [
      {
        "a1": 0,
        "a2": -1,
        "a3": 7
      },
      {
        "a1": 2,
        "a2": -3,
        "a3": 4
      }
    ]
  }
}

I want to transform it to:

{
  "dg" : {
    "gi" : 7          //7 is from d.a0.[first element from array].a3
  }
}

So i write spec like this

[
  {
    "operation": "shift",
    "spec": {
      "d": {
        "a0": {
          "[0]": {
            "a3": "dg.gi"
          }
        }
      }
    }
  }
]

Java code:

List<Object> specs = JsonUtils.classpathToList(spec);
Chainr chainr = Chainr.fromSpec(specs);
// transform the message
return (Map<String, Object>) chainr.transform(inputJSON);

But it returns null and I don't know why

I'm new to Jolt so I don't have much knowledge about it

Please help, thank you


Solution

  • You just can replace [0] with 0. eg. convert to

    [
      {
        "operation": "shift",
        "spec": {
          "d": {
            "a0": {
              "0": { // only the first index of the array "a0"
                     // btw, "*" might have been used if needed to represent all indexes
                "a3": "dg.gi"
              }
            }
          }
        }
      }
    ]
    

    The level, where "[0]": { resides currently , represents the indexes of the array a0 and we picked only the first ( the one with index 0 ) of them.

    demo 1 ( on the site http://jolt-demo.appspot.com/ ) :

    enter image description here

    But, yet the "[0]" representation might be used by prefixing the whole path with a @ such as

    [
      {
        "operation": "shift",
        "spec": {
          "@d.a0.[0].a3": "dg.gi"
        }
      }
    ]
    

    in order to get exactly the same result.

    demo 2 :

    enter image description here