Home > Software engineering >  Jolt transform JSON key/value into String Array
Jolt transform JSON key/value into String Array

Time:09-08

EDIT: The key names are dynamic and unknown.

I want to take an Object and create an String array that has each key and value concated together.

My keys contain underscores which I need to get rid of (I have that part working). I'm struggling to figure out the next step to join everything together. (I guess I'm missing how to reference key and value from RHS?)

Input:

{
  "object": {
    "key_1": [
      "A",
      "B"
    ],
    "key_2": [
      "C"
    ],
    "key_3": [
      "D",
      "E",
      "F"
    ]
  }
}

Desired Output:

{
  "results": [
    "key 1: A B",
    "key 2: C",
    "key 3: D E F"
  ]
}

Spec:

[
  {
    "operation": "shift",
    "spec": {
      "object": {
        "*_*": "results.&(0,1) &(0,2)",
        "*": "results.&"
      }
    }
  }
]

Current spec output:

{
  "results": {
    "key 1": [
      "A",
      "B"
    ],
    "key 2": [
      "C"
    ],
    "key 3": [
      "D",
      "E",
      "F"
    ]
  }
}

CodePudding user response:

Seems you need to use modify transformations with join functions, along with shift transformation specs such as

[
  {
   // combine the components of the each array with one extra whitespaces between them
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "*": "=join(' ',@(1,&))"
      }
    }
  },
  {
   // get rid of underscores
    "operation": "shift",
    "spec": {
      "*": {
        "*_*": "&1.&(0,1) &(0,2)"
      }
    }
  },
  {
    // generate new arrays with the first components are the keys, and second ones are the values of the previous attributes of the object
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "$": "&",
          "@": "&"
        }
      }
    }
  },
  {
   // get concatenated values for key-value pairs with colons between them
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=join(': ',@(1,&))"
    }
  },
  {
   // get the desired result as a single array
    "operation": "shift",
    "spec": {
      "*": {
        "@": "results[]"
      }
    }
  }
]

the demo on the site enter image description here

  • Related