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!

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

    报告相同问题?

    悬赏问题

    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥20 #关于multisim绘图遇到的问题
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程
    • ¥15 调制识别中输入为时频图,星座图,眼图等
    • ¥15 数据结构C++的循环、随机数问题