2016-03-06 124 views
1

在python中,您可以获取json对象并从中获取特定的项目,而无需声明结构,保存到结构中,然后像Go中那样获取值。 Go有没有包装或更简单的方法来存储json的特定值?Golang Json单值解析

蟒蛇

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

回答

5

可以解码为map[string]interface{},然后通过按键获取的元素。

data := make(map[string]interface{}) 
err := json.Unmarshal(content, &data) 
if err != nil { 
    return nil, err 
} 

price, ok := data["ask_price"].(string); !ok { 
    // ask_price is not a string 
    return nil, errors.New("wrong type") 
} 

// Use price as you wish 

结构往往是首选,因为它们更明确的类型。你只需要在你关心的JSON中声明这些字段,并且你不需要像使用map(encoding/json隐式处理)那样键入断言值。