JSON single value parsing

You can decode into a map[string]interface{} and then get the element by 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")
    }
}

Structs are often preferred as they are more explicit about the type. You only have to declare the fields in the JSON you care about, and you don’t need to type assert the values as you would with a map (encoding/json handles that implicitly).

Leave a Comment