JSON 单值解析 [英] JSON single value parsing

查看:23
本文介绍了JSON 单值解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

你可以解码成一个map[string]interface{},然后通过key来获取元素.

You can decode into a map[string]interface{} and then get the element by key.

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 隐式处理).

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

这篇关于JSON 单值解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆