【问题标题】:JSON single value parsingJSON单值解析
【发布时间】:2022-04-19 16:31:33
【问题描述】:

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

蟒蛇

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

【问题讨论】:

    标签: json go


    【解决方案1】:

    可以解码成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 中声明字段,而无需像使用地图那样键入断言值(编码/json 隐式处理)。

    【讨论】:

      【解决方案2】:

      尝试fastjsonjsonparserjsonparser 针对必须选择单个 JSON 字段的情况进行了优化,而 fastjson 针对必须选择多个不相关的 JSON 字段的情况进行了优化。

      下面是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")
      

      【讨论】:

        猜你喜欢
        • 2019-08-30
        • 2022-11-16
        • 2012-04-12
        • 2019-10-25
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多