Why struct isn’t getting any data on unmarshal in Go?

Among first few problems, a go lang programmer will probably be struggling with a blank struct. Structs have blank values when one of the following things are wrong:

1. Invalid Naming Conventions:

First letter of fields in struct should be capital. For example


//Invalid name 	
type Person struct {
    name string
    age  int
}

//Valid Name
type Person struct {
    Name string
    Age  int
}

2. Invalid Matches:

Consider this is the json which we can’t change.


{
 FirstName: "John Doe",
 Age: "30",
}

 


//Results in blank data 	
type Person struct {
    FirstName string //This will match first_name but we have FirstName
    Age  int //This will match age but we have Age
}

//The fix
type Person struct {
    FirstName string `json:"FirstName"`
    Age  int `json:"Age"`
}

Worth Sharing?

6 Comments

    1. Five second on renaming and 10 mins Googling. This alone article tells us what was wrong. This is not documented properly.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>