Search code examples
jsonapache-nifijolt

I need to transform a JSON into Key Value SON using jolt spec. What should be the right spec to do it?


Input JSON

{
  "Date": "6/3/2023 17:38",
  "Volt": 7,
  "WS1": 0,
  "WS2": 0,
  "HR1": 32.65,
  "T1": 20.35,
  "PY1": 7,
  "R1": 0
}

Output JSON

{
  "Date": "2023-03-06 17:38:",
  "data": [
    {
      "code": "Volt",
      "value": "7.0"
    },
    {
      "code": "WS1",
      "value": "0.0"
    },
    {
      "code": "WS2",
      "value": "0.0"
    },
    {
      "code": "HR1",
      "value": "32.65"
    },
    {
      "code": "T1",
      "value": "20.35"
    },
    {
      "code": "PY1",
      "value": "7.0"
    },
    {
      "code": "R1",
      "value": "0.0"
    }
  ]
}

Solution

  • You can use the following transformation

    [
      {
        "operation": "shift",
        "spec": {
          "Date": "&",
          "*": "others.&"
        }
      },
      {
        "operation": "shift",
        "spec": {
          "Date": "&",
          "others": { // attributes other than Date
            "*": {
              "$": "data[#2].code",
              "@": "data[#2].value"
            }
          }
        }
      },
      { // get the date as in the desired format
        "operation": "modify-overwrite-beta",
        "spec": {
          "Dt1": "=split(' ',@(1,Date))",
          "Dt2": "=split('/',@(1,Dt1[0]))",
          "Dtmon": "=leftPad(@(1,Dt2[1]), 2, '0')",
          "Dtday": "=leftPad(@(1,Dt2[0]), 2, '0')",
          "Date": "=concat(@(1,Dtday),'-',@(1,Dtmon),'-',@(1,Dt2[2]),' ',@(1,Dt1[1]))"
        }
      },
      { // get rid of the auxiliary generated elements
        "operation": "remove",
        "spec": {
          "Dt*": ""
        }
      }
    ]