JSON单值解析

huangapple go评论89阅读模式
英文:

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, &quote)
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或者jsonparserjsonparser在需要选择单个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")

huangapple
  • 本文由 发表于 2016年3月6日 09:43:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/35822102.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定