amazon-web-servicesmappingaws-api-gatewayapache-velocity

How to convert object to JSON in AWS API Gateway?


I have some simple data I want to transform with API Gateway:

{
    "data": [
        {"id":"1", "name":"Foo"},
        {"id":"2", "name":"Bar"},
        {"id":"3", "name":"Dead"},
        {"id":"4", "name":"Beef"}
    ]
}

I'm able to loop the data:

#foreach($elem in $input.path('$.data'))
    {
       "Data": $elem,
       "Foo": "Bar"
    }#if($foreach.hasNext),#end
#end

The expected result is:

{"Data": {"id":"1", "name":"Foo"}, "Foo": "Bar"},
{"Data": {"id":"2", "name":"Bar"}, "Foo": "Bar"},
{"Data": {"id":"3", "name":"Dead"}, "Foo": "Bar"},
{"Data": {"id":"4", "name":"Beef"}, "Foo": "Bar"}

However, the actual result is:

{"Data": {id=1, name=Foo}, "Foo": "Bar"},
{"Data": {id=2, name=Bar}, "Foo": "Bar"},
{"Data": {id=3, name=Dead}, "Foo": "Bar"},
{"Data": {id=4, name=Beef}, "Foo": "Bar"}

$elem produces {id=1, name=Foo} which seems to be what the objects are stringified as. I'd like to have it in JSON, how to I accomplish that?

I've tried $elem.stringify(), $input.json($elem) and $elem.json() but that doesn't work.


Solution

  • I came up with an odd work-around reading about the $index and how Apache Velocity works:

    #foreach($elem in $input.path('$.data'))
        #set($pathBegin = "$.data[")
        #set($pathEnd = "]")
        #set($currentIndex = $foreach.index)
        #set($thePath = "$pathBegin$currentIndex$pathEnd")
        #set($elemJson = $input.json($thePath)) 
      {
        "Data": $elemJson,
        "Foo": "Bar"
      }#if($foreach.hasNext),#end
    #end
    

    This could probably be more optimised but it actually works and prints out the expected result.