Search code examples
jsonjolt

Jolt transformation, if any field is null then set object value to null


I have a source JSON as below :

{
  "name": "test",
  "age" 10,
  "city": null,
  "pinCode": "400081",
  "address": {
    "buildingNo": "B-301"
  }
} 

if city is null, then update address to null such as :

"person" : {
    "name" : "test",
    "age" : 10,
    "address" : null
}

otherwise, if city is not null, then keep the result like this :

{
  "person" : {
    "name" : "test",
    "age" : 10,
    "address" : {
      "pinCode" : "400081",
      "buildingNo" : "B-301"
    }
  }
}

I have tried with jolt transform like below :

[
  {
    "operation": "shift",
    "spec": {
      "name": "person.name",
      "age": "person.age",
      "city": {
        "null": {
          "@(1,person.address)": null
        },
        "*": {
          "@1": "person.address.city"
        }
      },
      "pinCode": "person.address.pinCode",
      "address": {
        "buildingNo": "person.address.buildingNo"
      }
    }
  }
]

Solution

  • null is a predefined value, but "null" or "NulL" etc. are some arbitrary literals those are not identical. You might set city to a literal such as "NulL"within a modify spec. along with a ~ operator in order to be able use in a conditional within a shift spec. such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "~city": "NulL"
        }
      },
      {
        "operation": "shift",
        "spec": {
          "name|age": "person.&",
          "city": {
            "NulL": {
              "@": "person.address"
            },
            "*": {
              "@1": "person.address.&2", // bring value(@1) amd key(&2) of "city" attribute 
              "@2,pinCode": "person.address.pinCode",
              "@2,address": {
                "*": "person.address.&" // all elements in "address" object
              }
            }
          }
        }
      }
    ]