Golang Json单值解析

vin*_*iyo 2 json go

在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, &quote)
if errJson != nil {
    return "nil", fmt.Errorf("cannot read json body: %v", errJson)
}
Run Code Online (Sandbox Code Playgroud)

eli*_*rar 7

您可以解码为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隐式处理).

  • 这实际上不编译!https://play.golang.org/p/IN9vN3pfGui 这是正确的版本:https://play.golang.org/p/zh_qWbSkM5t (2认同)