Being a language built for the web, Go offers feature-rich support for working with JSON data. JSON (JavaScript Object Notation) is an unbelievably popular data interchange format whose syntax resembles simple JavaScript objects. It’s one of the most common ways for web applications to communicate.
Go takes a unique approach for working with JSON data. The best way to think about JSON data in Go is as an encoded struct
. When you encode and decode a struct to JSON, the key of the JSON object will be the name of the struct field unless you give the field an explicit JSON tag.
type User struct {
FirstName string `json:"first_name"` // key will be "first_name"
BirthYear int `json:"birth_year"` // key will be "birth_year"
Email string // key will be "Email"
}
The encoding/json
package exposes a json.Marshal
function that allows us to create the JSON encoding of any type, assuming that type has an encoder implemented. The good news is, all the default types have an encoder, and you’ll usually be working with structs filled with default-type fields.
func Marshal(v interface{}) ([]byte, error)
As you can see, Marshal()
takes a value as input, and returns the encoded JSON as a slice of bytes on success, or an error if something went wrong.
dat, _ := json.Marshal(User{
FirstName: "Lane",
BirthYear: 1990,
Email: "example@gmail.com",
})
fmt.Println(string(dat))
// prints:
// {"first_name":"Lane","birth_year":1990,"Email":"example@gmail.com"}
#golang #mailing-list #go