英文:
JSON single value parsing
问题
在Python中,你可以直接从JSON对象中获取特定的项,而无需声明结构体,保存到结构体然后获取值,就像在Go语言中那样。在Go语言中,有没有一种包或更简单的方法来存储JSON中的特定值?
Python:
res = res.json()
return res['results'][0]
Go语言:
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)
}
英文:
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?
python
res = res.json()
return res['results'][0]
Go
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)
}
答案1
得分: 11
你可以将其解码为map[string]interface{}
,然后通过键获取元素。
func main() {
b := []byte(`{"ask_price":"1.0"}`)
data := make(map[string]interface{})
err := json.Unmarshal(b, &data)
if err != nil {
panic(err)
}
if price, ok := data["ask_price"].(string); ok {
fmt.Println(price)
} else {
panic("wrong type")
}
}
通常情况下,更推荐使用结构体,因为它们对类型更明确。你只需要声明你关心的JSON字段,而不需要像使用map那样进行类型断言(encoding/json会隐式处理)。
英文:
You can decode into a map[string]interface{}
and then get the element by key.
func main() {
b := []byte(`{"ask_price":"1.0"}`)
data := make(map[string]interface{})
err := json.Unmarshal(b, &data)
if err != nil {
panic(err)
}
if price, ok := data["ask_price"].(string); ok {
fmt.Println(price)
} else {
panic("wrong type")
}
}
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).
答案2
得分: 3
尝试使用fastjson或者jsonparser。jsonparser
在需要选择单个JSON字段的情况下进行了优化,而fastjson
在需要选择多个不相关的JSON字段的情况下进行了优化。
以下是使用fastjson
的示例代码:
var p fastjson.Parser
v, err := p.Parse(content)
if err != nil {
log.Fatal(err)
}
// 将v["ask_price"]作为float64获取
price := v.GetFloat64("ask_price")
// 将v["results"][0]作为通用的JSON值获取
result0 := v.Get("results", "0")
英文:
Try either fastjson or jsonparser. jsonparser
is optimized for the case when a single JSON field must be selected, while fastjson
is optimized for the case when multiple unrelated JSON fields must be selected.
Below is an example code for fastjson
:
var p fastjson.Parser
v, err := p.Parse(content)
if err != nil {
log.Fatal(err)
}
// obtain v["ask_price"] as float64
price := v.GetFloat64("ask_price")
// obtain v["results"][0] as generic JSON value
result0 := v.Get("results", "0")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论