Search code examples
jsonjolt

Jolt Transformation for fetching value of map based on dynamic key


I have input like

{
  "searchType": "SR",
  "searchTypeMap": {
    "SR":"CREDIT_APPLICATION",
    "SQ":"CREDIT_QUOTATION",
    "DR": "DIRECTOR_CREDIT_SEARCH"
  }
}

Need to fetch the value CREDIT_APPLICATION based on the searchType = SR The output would look like below

{
  "searchType": "SR",
  "searchTypeValue": "CREDIT_APPLICATION",
  "searchTypeMap": {
    "SR":"CREDIT_APPLICATION",
    "SQ":"CREDIT_QUOTATION",
    "DR": "DIRECTOR_CREDIT_SEARCH"
  }
}

By hardcoding the value SR in spec below, I am able to get the output.

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "searchTypeMap": {
        "SR": {
          "@": "searchTypeValue",
          "@(1,&)": "searchTypeMap.&"
        },
        "*": {
          "@": "searchTypeMap.&"
        }
      }
    }
  }
]

But, The value of searchType can be anything at runtime like SR, SQ, DR. So, tried using dynamic value as below but not getting the desired output .

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "searchTypeMap": {
        "@(1,searchType)": {
          "@": "searchTypeValue",
          "@(1,&)": "searchTypeMap.&"
        },
        "*": {
          "@": "searchTypeMap.&"
        }
      }
    }
  }
]


Solution

  • You can use the following shift transformation spec :

    [
      {
        "operation": "shift",
        "spec": {
          "searchType": {
            "*": {
              "@2,searchTypeMap.&": "&2Value" //matches the value under searchTypeMap node by searchTypeMap.&
                                              //@2 represents going 2 levels up in order to reach the level of "searchType"
                                              //&2 replicates the literal "searchType" 
            },
            "@": "&" // the own value of "searchType"
          },
          "*": "&"// the elments other than "searchType", eg. "searchTypeMap" object
        }
      }
    ]
    

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

    enter image description here