Skip to content
Advertisement

Adding default values to array in 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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement