AWS Api Gateway 中的速度:如何访问对象数组

Posted

技术标签:

【中文标题】AWS Api Gateway 中的速度:如何访问对象数组【英文标题】:Velocity in AWS Api Gateway: how to access array of objects 【发布时间】:2020-11-22 21:14:56 【问题描述】:

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

https://pastebin.com/GpQady4Z

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

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

#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

为什么我的代码不能处理对象数组?

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

是的,我以前试过这个。这种方法的问题是我不能像这样迭代: $input.json('$.Items[$i]') 因为它不评估 $i 它也不适用于 foreach

以上是关于AWS Api Gateway 中的速度:如何访问对象数组的主要内容,如果未能解决你的问题,请参考以下文章