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!

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵