Go JSON Parsing: Methods Guide
In Go, there are several ways to parse JSON data:
- encoding in JSON
- json encoding
- Decode or parse
- Decode the data.
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
jsonStr := `{"name":"Alice","age":25}`
var person Person
err := json.Unmarshal([]byte(jsonStr), &person)
if err != nil {
panic(err)
}
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
- Parse the JSON data.
- parse the JSON data
- a data structure that stores values by using strings as keys
- Create a visual representation of geographical locations.
- unspecified type
- an array of bytes
- parse the JSON data
jsonStr := `{"name":"Alice","age":25}`
var data map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &data)
if err != nil {
panic(err)
}
fmt.Printf("Name: %s, Age: %f\n", data["name"].(string), data["age"].(float64))
- parsing JSON data
- Decode a JSON object
- Translate into plain text
- a decoder for JSON data
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
jsonStr := `{"name":"Alice","age":25}`
var person Person
dec := json.NewDecoder(strings.NewReader(jsonStr))
for {
if err := dec.Decode(&person); err == io.EOF {
break
} else if err != nil {
panic(err)
}
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
}
Regardless of the method used, it is necessary to handle errors when parsing JSON data to ensure the process is done correctly.