Neeraj
Neeraj

Reputation: 49

Conversion of if/else based JSON by using Jolt

I have two following json input and i want to convert it into expected output by jolt

input - 1

{
  "alert_array": {
    "alerts": [
      {
        "id": "1234",
        "data": {
          "parameter": [
            {
              "key": "level",
              "value": "93.5"
            }
          ]
        }
      }
    ]
  }
}

input - 2

{
  "alert_array": {
    "alerts": [
      {
        "id": "1234",
        "data": {}
      }
    ]
  }
}

expected output - 1

{
  "alertArray": [
    {
      "id": "1234",
      "properties": [
        {
          "key": "level",
          "value": "93.5"
        }
      ]
    }
  ]
}

expected output - 2

{
  "alertArray": [
    {
      "id": "1234",
      "properties": []
    }
  ]
}

In input-1 data contain some parameter but in input-2 data object is blank

Upvotes: 0

Views: 67

Answers (1)

Barbaros Özhan
Barbaros Özhan

Reputation: 65323

You can use default transformation along with shift transformations

in order to add "properties": [] for the empty case of "data" object for the both of the input

JSON values such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "alerts": {
          "*": {
            "id": "alertArray.&",
            "*": {
              "*": {
                "*": {
                  "id": "alertArray.properties[&1].key",
                  "*": "alertArray.properties[&1].&"
                }
              }
            }
          }
        }
      }
    }
  },
  {
    "operation": "default",
    "spec": {
      "*": {
        "properties": []
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&[]"
    }
  }
]

the demo for the first case :

enter image description here

the demo for the second case :

enter image description here

If there was no such need(to fill up for the "data"), then the following single spec would be sufficient :

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "alerts": {
          "*": {
            "id": "alertArray[&1].&",
            "*": {
              "*": {
                "*": {
                  "id": "alertArray[&4].properties[&1].key",
                  "*": "alertArray[&4].properties[&1].&"
                }
              }
            }
          }
        }
      }
    }
  }
]

Upvotes: 1

Related Questions