Search code examples
jsonjolt

jolt transformation to remove key if value is not present


I have an input json in the form of key, value pair. I don't want to include the key in the output if value for that key is missing. As in this input teacherid is missing, so it shouldn't be included in the ouput.

input :

{
  "alldetails": {
    "classid": 1,
    "schoolid": 3
  }
}

jolt spec :

[
  {
    "operation": "shift",
    "spec": {
      "alldetails": {
        "#Id_class": "data[0].source",
        "classid": "data[0].value",
        "#Id_teacher": "data[1].source",
        "teacherid": "data[1].value",
        "#Id_school": "data[2].source",
        "schoolid": "data[2].value"
      }
    }
  }
]

current output :

{
  "data": [
    {
      "source": "Id_class",
      "value": 1
    },
    {
      "source": "Id_teacher"
    },
    {
      "source": "Id_school",
      "value": 3
    }
  ]
}

desired output :

{
  "data": [
    {
      "source": "Id_class",
      "value": 1
    },
    {
      "source": "Id_school",
      "value": 3
    }
  ]
}

Any help would be appreciated. Thanks


Solution

  • https://jolt-demo.appspot.com/#inception runs on v0.1.1 which is old and don't support all features so created new on v0.1.6 https://vishavjeet6.github.io/jolt-transformer/

    This worked for me

    [
      {
        "operation": "shift",
        "spec": {
          "alldetails": {
            "classid": {
              "#Id_class": "data[0].source",
              "@(1,classid)": "data[0].value"
            },
            "teacherid": {
              "#Id_teacher": "data[1].source",
              "@(1,teacherid)": "data[1].value"
            },
            "schoolid": {
              "#Id_school": "data[2].source",
              "@(1,schoolid)": "data[2].value"
            }
          }
        }
      },
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": "=recursivelySquashNulls"
        }
      }
    ]
    

    enter image description here