-
Notifications
You must be signed in to change notification settings - Fork 3
JSON
JSON (JavaScript Object Notation) is an encoding of JavaScript values - strings, numbers, booleans, arrays and objects as unicode text. It is specified in RFC-4627.
Marshaling, converting from golang struct to a JSON string, uses Go struct fields names for JSON object keys through reflection. Only exported fields are marshaled. eg:
typedef Planets struct {
Name string `json:"name"`
GasGiant bool `json:"gas_giant,omitempty"`
}
Conversion from JSON string to struct fields is called Un-marshaling. It is enabled by golang reflection on struct tags. These string literal tags (eg: json:"name"
above) enable encoding/decoding from various formats like XML, ORM or your custom format. Go play struct tags.
JSON encoding package provides helpers to encode and decode structs types to json. This package provides two main mechanisms for converting from Go struct and JSON.
This provides mechanisms to convert from a Go data struct to JSON or visa-versa.
json.Marshal()
converts a Golang struct into []byte
of JSON values. The reverse operation of JSON to struct type is accomplished by json.Unmarshal()
json package.
The methods json.Encoder()
and json.Decoder()
provide stream APIs. These are efficient when we want to send JSON data to a Writer interface or read from a reader interface. For example, receiving data from a http.Request or sending in http.ResponseWriter interfaces.
See example:
// handler sends JSON data to a http.ResponseWriter
func handler(w http.ResponseWriter, r *http.Request) {
// Receive JSON. Do check if content is indeed "application/json" type
var data struct{}{}
_ := json.NewDecoder(r).decode(&data) // Receive the data. Ignore error
// Send data
w.Header().Set("Content-Type", "application/json") // Set content-type
_= json.NewEncoder(w).Encode(data) // Echo the data back. Ignore error
}