Encode and decode JSON in Go
Encode and decode JSON in Go
JSON is a text format for exchanging structured data. Marshal converts a Go value into JSON bytes; Unmarshal parses bytes into a destination supplied by pointer. Both return errors. The check helper stops these tiny examples on unexpected errors; in a service, return the error instead.
package main
import ( "encoding/json" "fmt")
func check(e error) { if e != nil { panic(e) }}
func main() { b, e := json.Marshal([]string{"tea", "rice"}) check(e) fmt.Println(string(b)) var items []string check(json.Unmarshal(b, &items)) fmt.Println(items[0], len(items))}Marshal returns []byte, not a string. Unmarshal needs a non-nil pointer so it can update the variable. A mismatched type or malformed document can fail; do not use partially decoded data after an error.
Expected output:
["tea","rice"]tea 2Inspect invalid input
package main
import ( "encoding/json" "fmt")
func main() { var n int e := json.Unmarshal([]byte(`"five"`), &n) fmt.Println(e != nil) fmt.Println(json.Valid([]byte(`{"n":5}`)), json.Valid([]byte(`{"n":}`)))}Valid checks JSON syntax only. It does not establish that the document matches the expected Go type or business rules. Decode and validate those rules separately.
Expected output:
truetrue falseTry it locally
Decode [3,4,5] into []int and print the sum.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 01: Encode and decode JSON in Go
Check the lesson objective before moving on.
What destination should Unmarshal receive for variable n?
What does json.Valid establish?