首页 > 文章列表 > JSON单值解析

JSON单值解析

golang
356 2023-03-08

问题内容

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

Python

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

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

正确答案

您可以解码为 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

结构通常是首选,因为它们对类型更明确。您只需要在您关心的 JSON 中声明字段,并且不需要像使用地图那样键入断言值(编码/json 隐式处理)。