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

查看:61
本文介绍了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?

python

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{},然后通过键获取元素.

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处理)那样键入assert值.

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天全站免登陆