在python中,你可以获取一个json对象并从中获取一个特定项而不声明一个结构,保存到一个结构然后获取像Go中的值.是否有一个包或更简单的方法来存储Go中的json特定值?
蟒蛇
res = res.json()
return res['results'][0]
Run Code Online (Sandbox Code Playgroud)
走
type Quotes struct {
AskPrice string `json:"ask_price"`
}
quote := new(Quotes)
errJson := json.Unmarshal(content, "e)
if errJson != nil {
return "nil", fmt.Errorf("cannot read json body: %v", errJson)
}
Run Code Online (Sandbox Code Playgroud)
您可以解码为a 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
Run Code Online (Sandbox Code Playgroud)
结构通常是首选,因为它们对类型更明确.您只需声明您关注的JSON中的字段,并且您不需要像使用map一样键入断言值(编码/ json隐式处理).
| 归档时间: |
|
| 查看次数: |
5451 次 |
| 最近记录: |