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 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗