JSON Encoding with encoding/json
data, err := json.Marshal(value)
err := json.Unmarshal(data, &target)
Marshaling a Struct to JSON
json.Marshal converts a Go value -- most commonly a struct -- into its JSON representation as a byte slice, using each exported field's name (or its json tag, if present) as the key.
Example: Marshaling a Struct to JSON
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"encoding/json"
"fmt"
)
// Define a struct type named Book
type Book struct {
Title string `json:"title"`
Pages int `json:"pages"`
}
// main is where the program starts running
func main() {
// Short declaration: create b and infer the type
b := Book{Title: "Learning Go", Pages: 320}
// Short declaration: create data, err and infer the type
data, err := json.Marshal(b)
// Handle the error if one occurred
if err != nil {
// Print the values followed by a newline
fmt.Println("error:", err)
return
}
fmt.Println(string(data))
}
Login to try C/C++/Java/PHP code in the editor
Unmarshaling JSON into a Struct
json.Unmarshal parses JSON-encoded bytes into a Go value, which must be passed as a pointer so the function can write the decoded data directly into it.
Example: Unmarshaling JSON into a Struct
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"encoding/json"
"fmt"
)
// Define a struct type named Book
type Book struct {
Title string `json:"title"`
Pages int `json:"pages"`
}
// main is where the program starts running
func main() {
// Short declaration: create data and infer the type
data := []byte(`{"title":"Go in Action","pages":300}`)
// Declare b with the zero value of its type
var b Book
// Run this block only if the condition is true
if err := json.Unmarshal(data, &b); err != nil {
// Print the values followed by a newline
fmt.Println("error:", err)
return
}
fmt.Println(b.Title, b.Pages)
}
Login to try C/C++/Java/PHP code in the editor
Pretty-Printing JSON
json.MarshalIndent works like Marshal but adds a prefix and indentation to each nested level, producing human-readable, formatted JSON instead of one compact line.
Example: Pretty-Printing JSON
// Every Go file belongs to a package; main builds an executable
package main
// Import the packages this program uses
import (
"encoding/json"
"fmt"
)
// Define a struct type named Config
type Config struct {
Host string `json:"host"`
Port int `json:"port"`
}
// main is where the program starts running
func main() {
// Short declaration: create c and infer the type
c := Config{Host: "localhost", Port: 8080}
// Short declaration: create data, _ and infer the type
data, _ := json.MarshalIndent(c, "", " ")
// Print the values followed by a newline
fmt.Println(string(data))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting struct fields must be exported (capitalized) to be visible to json.Marshal -- unexported fields are silently skipped.
- Passing a non-pointer to json.Unmarshal, which fails to actually populate the target since it needs to modify it in place.
- Ignoring the error returned by Marshal/Unmarshal, silently proceeding with incomplete or zero-valued data on malformed input.
- json.Marshal converts a Go value into its JSON-encoded byte representation.
- json.Unmarshal parses JSON bytes into a Go value, which must be passed as a pointer.
- Only exported struct fields are visible to encoding/json; struct tags control the JSON key names.
- json.MarshalIndent produces pretty-printed, indented JSON output for readability.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: