Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding default values to array in Jolt

Tags:

java

json

jolt

I am trying to transform a json using jolt, it's just adding some default values to an array.

the input looks like this:

{
  "valueA": "A",
  "valueB": "B"
}

The output should be:

{
  "listWithItems": [ 
    {
      "valA": "A",
      "valB": "B",
      "valC": "C"
    }
  ]
}

My spec looks right now:

[
  {
    "operation": "shift",
    "spec": {
      "valueA": "listWithItems[0].valA",
      "valueB": "listWithItems[0].valB"
    }
  },
  {
    "operation": "default",
    "spec": {
      "listWithItems": [
        {
          "valC": "valC"
        }
      ]
    }
  }
]

I just can't pass the valC to the listWithItems and haven't found anything in the documentation. Can someone help me with this?

Thank you in advance!

like image 961
Nicolas Jimenez Avatar asked Dec 17 '25 23:12

Nicolas Jimenez


1 Answers

One option would be changing the order of the transformations such as

[
  {
   // Add a default attribute "C" to the current object
    "operation": "default",
    "spec": {
      "valueC": "C"
    }
  },
  {
   // Nest all children of the object under "listWithItems" key name as an array
    "operation": "shift",
    "spec": {
      "*": "listWithItems[0].&"
    }
  }
]

enter image description here

Another option uses modify transformation such as

[
  {
   // Nest all of the current elements of the object under the "listWithItems" array 
    "operation": "shift",
    "spec": {
      "*": "listWithItems[0].&"
    }
  },
  {
   // Add new key-value pair to the array
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "*": {
          "valueC": "C"
        }
      }
    }
  }
]

enter image description here

You can check out https://github.com/bazaarvoice/jolt/releases/ as a source and https://jolt-demo.appspot.com/ as a playground.

like image 55
Barbaros Özhan Avatar answered Dec 20 '25 15:12

Barbaros Özhan