2

所以在 AWS Api Gateway 中,我正在查询我的 DynamoDB 并得到这个 JSON 作为回复:

https://pastebin.com/GpQady4Z

所以,Items 是一个由 3 个对象组成的数组。我需要提取这些对象的属性:TS、Key 和 CamID。

我在集成响应中使用速度。这是我的映射模板:

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

API 网关的结果:

{
"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 总是返回空值

在像这样的纯数组中:

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

“测试”返回 42

为什么我的代码不适用于对象数组?

4

1 回答 1

3

$items是一个 JSON 字符串(不是 JSON 对象),所以$items[0]没有意义。

如果要访问第一项,请使用$input.json('$.Items[0]').

如果要遍历它们,可以先使用将 JSON 字符串转换为对象$util.parseJson()

于 2020-08-02T18:44:04.370 回答