doulan8330
2019-06-11 06:46
浏览 107

在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!

    点赞 打赏 评论

相关推荐 更多相似问题