JSON single value parsing


In python you can take a json object and grab a specific item from it without declaring a struct, saving to a struct then obtaining the value like in Go. Is there a package or easier way to store a specific value from json in Go?


res = res.json()
return res['results'][0] 


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)


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 {

    if price, ok := data["ask_price"].(string); ok {
    } 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).

Answered By – elithrar

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.