3

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.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44

1 Answers1

2

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.

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
  • Thank you very much for the answer. This was what I was looking for. How can it be that this is the correct way to reverse a json object back to a json string. You could make this a oneliner when taking the answer [here](https://stackoverflow.com/a/43493056/1118905) into consideration. – LukeFilewalker May 04 '22 at 22:56