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
Susan SarandonOriginal
2024-12-16 04:34:12309browse

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] 

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)
}

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!

Statement:
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