Home > Software design >  Transform Dictionary to Object with JOLT
Transform Dictionary to Object with JOLT

Time:04-27

i want to use JOLT Transform to convert an dictionary to an JSON Object. Here below i demonstrate it with an example below.

There is in the root an Array which contains the results from different computers. "Computer1", "Computer2", and more.

This structure should be stay. I removed the 2nd and more array elemt which will reoccur in the same way with {...}.

Given Object:

[
  {
    "name": "Computer1",
    "events": {
      "counts": [
        {
          "countType": "CRITICAL",
          "count": 5
        },
        {
          "countType": "HIGH",
          "count": 12
        },
        {
          "countType": "LOW",
          "count": 40
        }
      ]
    },
    "processes": {
      "counts": [
        {
          "countType": "CRITICAL",
          "count": 0
        },
        {
          "countType": "HIGH",
          "count": 2
        },
        {
          "countType": "LOW",
          "count": 80
        }
      ]
    }
  },
{
  "name": "Computer2",
    "events": {...},...
}
]

Desired Output:

[
  {
    "name": "Computer1",
    "events": {
      "CRITICAL": 5,
      "HIGH": 12,
      "LOW": 40
    },
    "processes": {
      "CRITICAL": 0,
      "HIGH": 2,
      "LOW": 80
    }
  }
, {
    "name": "Computer2", 
    "events": {...},
    ...
  }
]

Please help to identify the right JOLT spec.

Thanks in advance Marcus

CodePudding user response:

You can use such a shift transformation specs

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "name": "&1.&",
        "events|processes": { // pipe represents "OR" logic
          "counts": {
            "*": {
              "@count": "&4.&3.@countType" // "&4" and "&3" represent going four and three level up the tree to grab the indices of the outermost level list and the key name of the objects("events" and "processes") respectively
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]
  • Related