doulan8330 2019-06-11 06:46
浏览 114
已采纳

在AWS Lambda中使用GoLang解析JSON

As part of an application we are building, one of the process steps is an AWS Lamda that captures a post request does some work with it, and then moves one. It has an API Gateway Request as a trigger and the body of this request would be a JSON String. I am having trouble parsing the JSON String to GoLang Object. Here is what I have:

The function that catches request:

func HandleRequest(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

  log.Print(fmt.Sprintf("body:[%s] ", event.Body))

  parseResponseStringToTypedObject(event.Body)

  return events.APIGatewayProxyResponse{
     StatusCode: http.StatusOK,
     Body:       "OK",
  },  nil
}

Then the parseResponseStringToTypedObject function :

func parseResponseStringToTypedObject(responseString string) {

  b := []byte(responseString)
  var resp SimpleType
  err := json.Unmarshal(b, &resp)

  if err == nil {
      log.Print(fmt.Sprintf("Account Name: [%s]", resp.accountName))
  } else {
      log.Print(fmt.Sprintf("Could not unmarshall JSON string: [%s]", err.Error()))
  }
}

Here is the SimpleType struct:

type SimpleType struct {
  accountName string `json:accountName`
  amount      int    `json:amount`
}

I then, as a test, posted this JSON Body via Postman: enter image description here

I opened up the CloudWatch Logs (where my lamda logs to) and see that the body is present in the event.Body property, and then logging out a field in the unmarshalled object (resp.accountName) I note that the field is blank. Why is this? Here is log output for the request:

enter image description here

  • 写回答

1条回答 默认 最新

  • dougu3290 2019-06-11 07:08
    关注

    Your SimpleType struct needs 2 things here...

    1) The properties need to be "public" or "exported". Meaning they need to start with an upper cased character.

    AND

    2) The properties need proper tags for the serialization and de serialization of JSON. e.g. each JSON tag surrounded by "

    type SimpleType struct {
      AccountName string `json:"accountName"`
      Amount int `json:"amount"`
    }
    

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价