Search code examples
jsonjolt

JOLT specification Trim payload.parameters.name based on mentioned requirement


For the below input JSON

{
  "payload": {
    "version": "1",
    "parameters": [
      {
        "name": "a.b.c.d e.=f+g-h.i.j.1_2.dist [km]",
        "value": 0,
        "quality": false,
        "timestamp": 1688997493042
      },
      {
        "name": "a.b.c.d e.=f+g-h.i.j.1_2.time [sec]",
        "value": 0,
        "quality": false,
        "timestamp": 1688997493059
      }
    ],
    "eventType": "EVENT",
    "eventTime": 1690452924457
  }
}

I want to have an output JSON where I can trim payload.parameters.name for example have something like

{
  "payload": {
    "version": "1",
    "parameters": [
      {
        "name": "1_2.dist [km]",
        "value": 0,
        "quality": false,
        "timestamp": 1688997493042
      },
      {
        "name": "1_2.time [sec]",
        "value": 0,
        "quality": false,
        "timestamp": 1688997493059
      }
    ],
    "eventType": "EVENT",
    "eventTime": 1690452924457
  }
}

I tried few approach but was unable to transform in the required format

I tried following specification

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "$": "payload",
      "parameters": {
        "*": {
          "name": {
            "#trimLast": {
              "input": "payload.parameters[&3].name",
              "separator": "."
            }
          }
        }
      }
    }
  }
]

But it didn't fetch me required output

Note that : the part a.b.c.d e.=f+g-h.i.j. is common for all the objects in param list, my goal is to remove that part from the name.


Solution

  • You can split by the literal i.j. (i\\.j\\. along with escape characters), and pick up the lastElement from the newly formed array within a modify transformation such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "payload": {
            "parameters": {
              "*": {
                "n0": "=split('i\\.j\\.',@(1,name))",
                "name": "=lastElement(@(1,n0))"
              }
            }
          }
        }
      },
      { // get rid of the extra element "n0"
        "operation": "remove",
        "spec": {
          "payload": {
            "parameters": {
              "*": {
                "n0": ""
              }
            }
          }
        }
      }
    ]
    

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

    enter image description here