golang: Marshalling Struct into JSON

Categories: Blog

You might be here because an AWS error when trying to save to DynamoDB similar to this:

ValidationException: One or more parameter values were invalid: Missing the key id in the item
status code: 400, request id: 29URI3A5PNH12CFDGTFA261O11VV4KQNSO5AEMVJF66Q9ASUBBNF

or just trying to figure out why your json structure doesn’t have certain fields after marshalling.

In go if you have the following structure and are trying to fill it and marshalling like this:

type DBItem struct {
	id        int     `json:"id"`
	date      int     `json:"date"`
	etype     string  `json:"etype"`
	other     string  `json:"other"`
}

item := DBItem {
	id:    1200,
	date:  9823123123,
	etype: "type 1",
	other: "Other Value",
}

av, err := dynamodbattribute.MarshalMap(item)
fmt.Printf("after: %+v", av)

json, _ := json.MarshalIndent(response, "", "  ")
fmt.Printf("after: %s", json)

You are going to get the following output:

after: map[]
after: {}

An empty structure. This is happening because in golang whenever the field is lowercase means it will not be exported, in order to fix this you just need to change the field names in the structure to uppercase, like this:

type DBItem struct {
	Id        int     `json:"id"`
	Date      int     `json:"date"`
	Etype     string  `json:"etype"`
	Other     string  `json:"other"`
}

item := DBItem {
	Id:    1200,
	Date:  9823123123,
	Etype: "type 1"
}

av, err := dynamodbattribute.MarshalMap(item)
fmt.Printf("after: %+v", av)

json, _ := json.MarshalIndent(response, "", "  ")
fmt.Printf("after: %s", json)

This will get you:

after: map[other:{
  NULL: true
} date:{
  N: "0"
} etype:{
  S: "type 1"
} id:{
  N: "1"
}]

after: {
  "id": 1,
  "date": 0,
  "etype": "Expense Type",
  "other": ""
}

Done!

«

    Leave a Reply

    Your email address will not be published. Required fields are marked *