使用映射模板AWS API 网关在 JSON 对象上添加或更新属性

问题描述

在我的 AWS APIGW Rest API 中,我尝试在提交的请求正文 (JSON) 上添加和/或更新属性。我能找到的每个例子都涉及构建一个新的 JSON 对象,而不是更新现有的对象。

在集成请求映射模板中,我的传入数据体如下所示。如果是发布的新对象,则不会有 ID。如果它是一个现有的对象,它将有一个 ID。 此处的目标是通过获取现有 ID 并将其设置回 JSON 对象或添加新 ID 来始终确保它具有 ID

// New object getting added,No ID
{
    "first_name" : "Toby","last_name" : "Keith"
}


// Existing object getting updated,Has ID
{
    "id" : "abcdef"
    "first_name" : "Toby","last_name" : "Keith"
}

我的集成请求映射模板如下所示:

## Do we have an existing id? (this is correctly pulling the existing ID)
#set( $id = $input.path('$.id') )
## If no ID,create one using the RequestID.  (This is also working)
#if ( $id == "" ) #set( $id = $context.requestId ) #end
## Get the entire json request string as json object
#set( $json_obj = $input.json('$') )
## Overwrite the ID on the json body to make sure we always have one
## [HERE IS THE PROBLEM]
## This isn't setting the id back on the $json_obj
#set( $input.path('$.id') = "$id" )
{
    "data": "$util.escapeJavaScript($json_obj).replaceAll("\\'","'")"
}

我希望上面“数据”的值是一个 JSON 字符串,其中包含一个 id 以及 first_name 和 last_name。

我已经尝试了许多设置属性的变体,但到目前为止还没有运气。这些都不起作用。

// Tries to update the JSON string I think,not the $json_obj
#set( $input.path('$.id') = "$id" )
// These cause error (because of quotes?)
#set( "$json_obj.id" = "BBBB" )
#set( '$json_obj.id' = "CCCC" )
// Doesn't work
#set( $input.path("$json_obj.id") = "dddd" )
#set( $json_obj.id = "EEEE" )

作为 B 计划,我可以将 $json_obj 分解为键/值对,并遍历它们检查 ID 并添加或更新它。本质上是构建一个新的 JSON 对象,但这似乎比直接设置属性更不理想。

有谁知道如何使用映射模板在 JSON 对象上添加/更新属性

解决方法

我发现了这个问题。这一行并没有像我想象的那样将正文有效负载转换为 JSON 对象。在更仔细地阅读 documentation 之后,我看到它检查了一个 JSON 路径表达式并返回一个匹配的 JSON 字符串。

#set( $json_obj = $input.json('$') )

要将其转换为对象,我需要以下语法:

#set( $json_obj = $util.parseJson($input.json('$')) )

更正后的映射模板现在看起来像这样

## Do we have an existing id? (this is correctly pulling the existing ID)
#set( $id = $input.path('$.id') )
## If no ID,create one using the RequestID.  (This is also working)
#if ( $id == "" ) #set( $id = $context.requestId ) #end
## Get the entire json request string as json object
#set( $json_obj = $util.parseJson($input.json('$')) )
## Overwrite the ID on the json body to make sure we always have one
## This isn't setting the id back on the $json_obj
#set( $input.path('$.id') = "$id" )
{
    "data": "$util.escapeJavaScript($json_obj).replaceAll("\\'","'")"
}

然而,这会导致现在将 JSON 对象转换回格式正确的 JSON 字符串的次要问题。如果我打印出 JSON 对象,我会因为某种原因得到未加引号的字符串。

# Print out $json_obj 
$page_obj

结果

{first_name=Toby,last_name=Keith}

如果我无法解决该问题,我将针对该问题提出一个新问题。