aws-api-gateway - 如何使用 aws api 网关的速度模板转换 json 中的数组?
问题描述
我一直在为 aws api-gateway 编写速度模板,以转换来自我的 api 的 json 响应,从而为用户提供一致的响应。
我一直在尝试转换这个json:
{
"amountCharges": [
"charge1", "charge2", "charge3"
]
}
对于这个预期的:
{
"charges": [
"charge1", "charge2", "charge3"
]
}
我已经能够使用这个模板为对象创建一个数组:
#set( $inputRoot = $input.path('$') )
"charges": [
#foreach( $charge in $inputRoot.charges )
{
"type": "$charge.chargeType",
"name": "$charge.chargeName",
"amount": {
"value": $charge.chargeAmount.amountValue,
"currency": "$charge.chargeAmount.amountCurrency"
},
#if( $charge.chargeTax )
"tax": {
"name": "$charge.chargeTax.taxName",
"amount": {
"value": $charge.chargeTax.taxAmount.amountValue,
"currency": "$charge.chargeTax.taxAmount.amountCurrency"
}
}
#end
}
#if( $foreach.hasnext ) , #end
#end
]
虽然这个模板已经能够将我的 json 对象数组转换为所需的响应。下面提到的例子:
{
"charges": [
{
"chargeType": "someType1",
"chargeName": "someName1",
"chargeAmount": {
"amountValue": 5,
"amountCurrency": "someCurrency1"
},
"chargeTax": {
"taxName": "someTax1",
"taxAmount": {
"amountValue": 5,
"amountCurrency": "someCurrency1"
}
}
},
{
"chargeType": "someType2",
"chargeName": "someName2",
"chargeAmount": {
"amountValue": 10,
"amountCurrency": "someCurrency2"
}
}
]
}
模板将此 json 转换为预期的输出:
{
"charges": [
{
"type": "someType1",
"name": "someName1",
"amount": {
"value": 5,
"currency": "someCurrency1"
},
"tax": {
"name": "someTax1",
"amount": {
"value": 5,
"currency": "someCurrency1"
}
}
},
{
"type": "someType2",
"name": "someName2",
"amount": {
"value": 10,
"currency": "someCurrency2"
}
}
]
}
基本上,我想转换一个字符串数组,而不是一个键值对。任何线索都会有所帮助。提前致谢。
解决方案
我只需要一个简单的调整:
#set( $inputRoot = $input.path('$') )
"charges": [
#foreach( $amountCharge in $inputRoot.amountCharges )
"$amountCharge"
#if( $foreach.count < $inputRoot.amountCharges.size() ) , #end\
#end
]
推荐阅读
- python - 试图做一个简单的比较,在涉及RFID的python中,没有比较成功
- css - 需要带有 react-zoom-pan-pinch 的无限图表板
- c# - C#,String 的 Split() 方法从字符串中获取特定信息
- python-3.x - 使用 youtube-dl 搜索 Youtube 视频
- php - 如何修复此错误?ErrorException 使用未定义的常量 staff - 假定为“staff”(这将在 PHP 的未来版本中引发错误)
- c++ - 在 C++ 块范围内,重用堆栈内存是优化区域吗?
- google-cloud-dataflow - 无法为 asia-southeast1 区域中的 TestDataflowRunner 配置工作器
- c - C 字符串指针。int 指针 vs char 指针
- python - 为什么在这个简单的python函数中IDE会出现未绑定变量错误警告
- javascript - setTimeout 的重播按钮