Search code examples
jsonreferencemappingjolt

JOLT transformation for references


I'm looking for a JOLT transformation for replacing a reference by it's entity:

My input is as follows:

{
  "users": [
    {
      "id": 1,
      "firstname": "Max"
    },
    {
      "id": 4,
      "firstname": "Mel"
    }
  ],
  "special-role": {
    "id": 4
  }
}

My expected output should be:

{
  "special-role" : {
     "firstname": "Mel"
  }
}

There is already an example on SO A JOLT transformation question about mapping reference but I couldn't figure out the solution for my problem anyway. I haven't yet find out how to substitute the fixed value "4" in "@(2,users.4.firstname)": "&" by the value under

"special-role": {
    "id": 4
}

My latest try of the spec was:

[
  {
    "operation": "shift",
    "spec": {
      "users": {
        "*": {
          "*": "&2.@(1,id).&"
        }
      },
      "special-role": "&"
    }
  },   
  {
    "operation": "shift",
    "spec": {
      "special-role": {
        "id": {
          "@(2,users.4.firstname)": "&"
        }
      }
    }
  }
]

Solution

    • The outermost layer ( &2 ) on the RHS for the first transformation is redundant
    • The integer keys of the objects( &2 ) on the RHS might be matched with the value of special-role ( @(2,&) ) on the LHS within the second transformation

    So, you can use :

    [
      {
        "operation": "shift",
        "spec": {
          "users": {
            "*": {
              "fir*": "@(1,id).&" // pick the attribute "firstname" only
            }
          },
          "*": { // case of "special-role"
            "*": "&1"
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "@(2,&)": "&2"
            }
          }
        }
      }
    ]
    

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

    enter image description here