【问题标题】:Is it possible to add all stages variables into the body mapping template in a nested JSON structure?是否可以将所有阶段变量添加到嵌套 JSON 结构中的主体映射模板中?
【发布时间】:2017-11-24 06:26:11
【问题描述】:

我正在使用 API 网关,并且有一个将数据传递给 Step Function 的服务。

Steps 函数需要以下格式的 JSON 输入:

{ 
    "input":"", 
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}

我目前正在以手动方式传递阶段变量,即

#set($data = $util.escapeJavaScript($input.json('$')))
{ 
    "input": "{ 
        \"input\": $data, 
        \"stageVariables\" : { 
            \"clientId\": \"${stageVariables.clientId}\", 
            \"clientSecret\": \"${stageVariables.clientSecret}\", 
            \"password\": \"${stageVariables.password}\" },
    "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
}

我知道在默认映射模板中,您可以使用类似这样的方法来遍历阶段变量并生成 JSON:

"stage-variables" : {
#foreach($key in $stageVariables.keySet())
    "$key" : "$util.escapeJavaScript($stageVariables.get($key))"
    #if($foreach.hasNext),#end
#end
}

但是,Step Function 所需的 JSON 略有不同。如何在无需手动显式添加每个阶段的情况下将所有阶段变量转换为 JSON 格式?

谢谢

【问题讨论】:

    标签: json amazon-web-services aws-api-gateway vtl


    【解决方案1】:

    以下是有效的解决方案。好像模板对换行很敏感,注意下面的代码一共5行。

    #set($data = $util.escapeJavaScript($input.json('$')))
    {
        "input": "{ \"input\": $data, \"stageVariables\" : { #foreach($key in $stageVariables.keySet()) \"$key\" : \"$util.escapeJavaScript($stageVariables.get($key))\" #if($foreach.hasNext),#end #end } }",
        "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
    }
    

    【讨论】:

      【解决方案2】:

      我认为这应该可行,但我没有测试它。我只是复制了你在那里的 foreach 块并转义了内联引号。

      #set($data = $util.escapeJavaScript($input.json('$')))
      { 
          "input": "{ 
              \"input\": $data, 
              \"stageVariables\" : {
                  #foreach($key in $stageVariables.keySet())
                  \"$key\" : \"$util.escapeJavaScript($stageVariables.get($key))\"
                  #if($foreach.hasNext),#end
                  #end
              },
          "stateMachineArn": "arn:aws:states:eu-west-1:xxxxxxxxxxxx:stateMachine:StateMachine-1"
      }
      

      【讨论】:

      • 感谢您的回复@JackKohn,请参阅我发布的问题的答案。亲切的问候。
      猜你喜欢
      • 2023-01-11
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2020-09-01
      相关资源
      最近更新 更多