Search code examples
transformationjolt

Jolt Transformation - keep JSON structure even if object is empty


I have input json like this Input json 1

  {
  "globalRoute": [
    {
      "id": 527763,
      "attributes": {
        "arrival": {
          "date": "2024-03-18T15:23:00.000Z",
          "timezone": "America/New_York"
        }
      },
      "_operation": 1
    }
  ]
}

expected Output

{
  "global_route" : {
    "ship_locations" : [ {
      "global_ship_location_id" : 527763,
      "attributes" : {
        "arrival" : {
          "date" : "2024-03-18T15:23:00.000Z",
          "timezone" : "America/New_York"
        }
      },
      "_operation" : 1
    } ]
  }
}

I have written jolt spec that is working fine for this use case.

Jolt Spec

[
  {
    "operation": "shift",
    "spec": {
      "globalRoute": {
        "*": {
          "id": "global_route.ship_locations[&1].global_ship_location_id",
          "attributes": {
            "arrival": {
              "date": "global_route.ship_locations[&3].attributes.arrival.date",
              "timezone": "global_route.ship_locations[&3].attributes.arrival.timezone"
            },
            "departed": {
              "date": "global_route.ship_locations[&3].attributes.departed.date",
              "timezone": "global_route.ship_locations[&3].attributes.departed.timezone"
            }
          },
          "_operation": "global_route.ship_locations[&1]._operation"
        }
      }
    }
  }
]

Now Input Json 2

Input json 1

{
  "globalRoute": [
    {
      "id": 527763,
      "attributes": {
        "arrival": {
        }
      },
      "_operation": 1
    }
  ]
}

Expected Output

{
  "global_route" : {
    "ship_locations" : [ {
      "global_ship_location_id" : 527763,
      "attributes" : {
        "arrival" : {
        }
      },
      "_operation" : 1
    } ]
  }
}

But My current jolt spec is removing attributes object. How to keep as it is if it is passed empty json. Please help me with correct jolt spec so that if i pass empty json in attributes it should support and otherwise what data we are passing should be transformed..


Solution

  • Use the below spec, hope this will be helpful for you

    [
      {
        "operation": "shift",
        "spec": {
          "globalRoute": {
            "*": {
              "id": "global_route.ship_locations[#3].global_ship_location_id",
              "*": "global_route.ship_locations[#3].&"
            }
          }
        }
      }
    ]