Efficient JSON Single Value Parsing in Go
In Python, accessing a specific value from a JSON object is straightforward, as illustrated in the provided example:
res = res.json() return res['results'][0]
However, Go requires a more verbose approach of declaring a struct and unmarshaling the JSON into it:
type Quotes struct { AskPrice string `json:"ask_price"` } quote := new(Quotes) errJson := json.Unmarshal(content, "e) if errJson != nil { return "nil", fmt.Errorf("cannot read json body: %v", errJson) }
For greater simplicity in Go, consider decoding the JSON into a map[string]interface{} and accessing the desired value by its key:
func main() { b := []byte(`{"ask_price":"1.0"}`) data := make(map[string]interface{}) err := json.Unmarshal(b, &data) if err != nil { panic(err) } if price, ok := data["ask_price"].(string); ok { fmt.Println(price) } else { panic("wrong type") } }
While maps provide flexibility, structs remain preferable due to their explicit type declarations. They simplify the code by eliminating the need for type assertions.
The above is the detailed content of How Can I Efficiently Parse Single JSON Values in Go?. For more information, please follow other related articles on the PHP Chinese website!