Carven
Carven

Reputation: 15660

How to add a field to an existing JSON in Velocity?

I have a JSON coming from a request body and I'm trying to use VTL to map it by adding an additional field to it. The request body looks like this:

{
   "name": "John",
   "age": 20,
   "address": {
      "street": "Albert's Street",
      "City": "Test City"
   }
}

In AWS, I'm trying to map this request body to have an additional field which is coming from a parameter in the URL path to become this:

{
   "name": "John",
   "age": 20,
   "address": {
      "street": "Albert's Street",
      "City": "Test City"
   },
   "operation": "$input.params('path.operation')"
}

I have tried looping through with something like this but it doesn't work very well:

#set($allParams = $input.path('$'))
{
#foreach($type in $allParams.keySet())
    #set($params = $allParams.get($type))
"$type" : {
    #foreach($paramName in $params.keySet())
    "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
        #if($foreach.hasNext),#end
    #end
}
    #if($foreach.hasNext),#end
#end
}

Moreover, this only works for those with 2 levels in the JSON. It doesn't work for those at the first level of the JSON or if I happen to have more than 2 levels in the JSON payload.

All I need is simply appending one more field into the existing request body of a JSON payload. How can I do that in Velocity?

Upvotes: 1

Views: 1365

Answers (1)

Zac Charles
Zac Charles

Reputation: 1267

You can add a operation property to the input JSON like this:

#set ($input.path('$').operation = 'example')
$input.json('$')

The above results in the following for your example:

{
  "name": "John",
  "age": 20,
  "address": {
    "street": "Albert's Street",
    "City": "Test City"
  },
  "operation": "example"
}

Of course, you can use a value from params instead of 'example'.

By the way, consider running the param through $util.escapeJavaScript for added security.

Upvotes: 2

Related Questions