Search code examples
aws-api-gatewayvelocityvtl

Velocity in AWS Api Gateway: how to access array of objects


So in AWS Api Gateway, I'm querying my DynamoDB and gets this JSON as reply:

https://pastebin.com/GpQady4Z

So, Items is an array of 3 objects. I need to extract the properties of those objects: TS, Key and CamID.

I'm using Velocity in the Integration Response. Here is my Mapping Template:

#set($count = $input.json('$.Count'))
#set($items = $input.json('$.Items'))
{
"count" : $count,
"items" : $items,
"first_item": $items[0]
},

The result from API Gateway:

{
"count" : 3,
"items" : [{"TS":{"N":"1599050893346"},"Key":{"S":"000000/000000_2020-08-02-12.48.13.775-CEST.mp4"},"CamID":{"S":"000000"}},{"TS":{"N":"1599051001832"},"Key":{"S":"000000/000000_2020-08-02-12.50.01.220-CEST.mp4"},"CamID":{"S":"000000"}},{"TS":{"N":"1599051082769"},"Key":{"S":"000000/000000_2020-08-02-12.51.22.208-CEST.mp4"},"CamID":{"S":"000000"}}],
"first_item": 
}

first_item always returns empty value

While in a pure array like this:

#set($foo = [ 42, "a string", 21, $myVar ])
"test" : $foo[0]

"test" returns 42

Why is my code not working on array of objects?


Solution

  • $items is a JSON string (not JSON object), so $items[0] doesn't make sense.

    If you want to access the first item, use $input.json('$.Items[0]').

    If you want to iterate over them, you can convert the JSON string to object first using $util.parseJson()