Summary - encoding/json
- Go course
- Intermediate
- Lesson 64/80
- 4 min
Combine Marshal, Unmarshal and tags to write a record.
encoding/json summary
In memory: json.Marshal / json.Unmarshal(&v). In streams: json.NewEncoder(w).Encode / json.NewDecoder(r).Decode. Tags: json:"ad", omitempty, -. Data of unknown shape: map[string]any (numbers are float64) or json.RawMessage. Pointer fields to tell missing from zero.
Custom MarshalJSON
Keeping a money amount in cents but showing decimal text in JSON:
type Para int64 // cents
func (p Para) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d.%02d"`, p/100, p%100)), nil
}
json.Marshal(map[string]Para{"tutar": 1250}) // {"tutar":"12.50"}A MarshalJSON written with a value receiver works for both values and pointers.
Practice Money type
Write the Para type and its MarshalJSON method above. Encode map[string]Para{"tutar": 1250} and print it.
Starter code
package main
import (
"encoding/json"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"encoding/json"
"fmt"
)
type Para int64
func (p Para) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d.%02d"`, p/100, p%100)), nil
}
func main() {
b, err := json.Marshal(map[string]Para{"tutar": 1250})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}Expected output
{"tutar":"12.50"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does a type define its own JSON format?
- Only with tags
- It isn't possible
- By implementing MarshalJSON / UnmarshalJSON methods Correct answer
- By writing String()
Explanation: Types implementing the json.Marshaler and json.Unmarshaler interfaces control encoding entirely themselves.
2 Readable output
b, _ := json.____(v, "", " ")
b, _ := json.MarshalIndent(v, "", " ")
Explanation: MarshalIndent writes JSON on multiple lines with the given indentation.
3 Group summary
| Term | Meaning |
|---|---|
Marshal |
Go → JSON |
Unmarshal |
JSON → Go |
omitempty |
Skip zero |
MarshalJSON |
Custom format |