Go JSON Parsing: Methods Guide

In Go, there are several ways to parse JSON data:

  1. encoding in JSON
  2. json encoding
  3. Decode or parse
  4. 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)
  1. Parse the JSON data.
  2. parse the JSON data
  3. a data structure that stores values by using strings as keys
  4. Create a visual representation of geographical locations.
  5. unspecified type
  6. an array of bytes
  7. 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))
  1. parsing JSON data
  2. Decode a JSON object
  3. Translate into plain text
  4. 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.

bannerAds