Link Search Menu Expand Document

8.1 JSON

While implementing your client app, you will want to perform a variety of operations on data represented by Go structs. However, when saving/loading data to/from Datastore or using one of the Cryptographic Functions, you’ll need a way to convert between structs and byte slices.

To transform a Go struct into a byte slice, you will serialize the Go struct into JSON. To do this, you will use the json.Marshal() and json.Unmarshal() functions, from the Go JSON library.

Note that Marshal supports encoding any JSON-compatible data types (including strings, booleans, and integers). Read more here.


Functions

json.Marshal(v interface{}) (bytes []byte, err error)

Converts an arbitrary Go value into a byte slice containing the JSON representation of the struct.

Only public fields are converted. Private fields (fields starting with a lowercase letter) are not marshaled into the output. This function will automatically follow pointers and nested pointers when marshalling.

Parameters
v (interface{}) - value to be serialized to JSON (can be any data type)

Returns
bytes ([]byte), err (error)

Example:

// Serialize a User struct into JSON.
type User struct {
     Username string
     Password string
     secret   int
}

alice := &User{
 "alice",
 "password",
 42,
}

aliceBytes, err := json.Marshal(alice)
userlib.DebugMsg("%s\n", string(bytes))
// {"Username":"alice","Password":"password"}


json.Unmarshal(v []byte, obj interface{}) (err)

Converts a byte slice generated by json.Marshal back into a Go struct.

Public fields are restored if present, and private fields will be default-initialized.

This function automatically generates nested pointers where needed to generate a valid struct.

This function will return an error if there is a type mismatch between the JSON and the struct (e.g. storing a string into a number field in a struct).

Parameters
v ([]byte) - output from a call to json.Marshal
obj (interface{}) - pointer to the Go struct where values will be loaded

Returns
err (error)

Example:

// Serialize a User struct into JSON.
type User struct {
     Username string
     Password string
     secret   int
}

aliceBytes := []byte("{\"Username\":\"alice\",\"Password\":\"password\"}")
 var alice User
 err = json.Unmarshal(aliceBytes, &alice)
 if err != nil { return }

userlib.DebugMsg("%v\n", alice)
// {alice password 0}