Home > Backend Development > Golang > How Can I Efficiently Parse Single JSON Values in Go?

How Can I Efficiently Parse Single JSON Values in Go?

Susan Sarandon
Release: 2024-12-16 04:34:12
Original
307 people have browsed it

How Can I Efficiently Parse Single JSON Values in Go?

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] 
Copy after login

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, &quote)
if errJson != nil {
    return "nil", fmt.Errorf("cannot read json body: %v", errJson)
}
Copy after login

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")
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template