登录
首页 >  Golang >  Go问答

检查 JSON 值的类型在 Go 中解组

来源:stackoverflow

时间:2024-02-26 08:51:22 306浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《检查 JSON 值的类型在 Go 中解组》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我正在使用一个通常提供 json 字符串值的 api,但它们有时会提供数字。例如,99% 的情况是这样的:

{
    "description": "doorknob",
    "amount": "3.25"
}

但无论出于何种原因,有时会是这样的:

{
    "description": "lightbulb",
    "amount": 4.70
}

这是我正在使用的结构,它在 99% 的情况下都有效:

type Cart struct {
    Description string `json:"Description"`
    Amount      string `json:"Amount"`
}

但是当他们提供数字金额时它就会崩溃。解组结构时进行类型检查的最佳方法是什么?

演示:https://play.golang.org/p/s_gp2sqc5-a


解决方案


对于一般情况,您可以使用 interface{},如 Burak Serdar's answer 中所述。

对于数字,有 json.Number 类型:它接受 json 数字和 json 字符串,并且如果以 Number.Int64()Number.Float64() 的字符串形式给出数字,它可以“自动”解析该数字。不需要自定义编组器/解组器。 p>

type cart struct {
    description string      `json:"description"`
    amount      json.number `json:"amount"`
}

测试它:

var (
    cart1 = []byte(`{
    "description": "doorknob",
    "amount": "3.25"
}`)

    cart2 = []byte(`{
    "description": "lightbulb",
    "amount": 4.70
}`)
)

func main() {
    var c1, c2 cart
    if err := json.unmarshal(cart1, &c1); err != nil {
        panic(err)
    }
    fmt.printf("%+v\n", c1)
    if err := json.unmarshal(cart2, &c2); err != nil {
        panic(err)
    }
    fmt.printf("%+v\n", c2)
}

输出(在 Go Playground 上尝试):

{description:doorknob amount:3.25}
{description:lightbulb amount:4.70}

如果该字段可以是字符串或整数,您可以使用接口{},然后计算出底层值:

type Cart struct {
    Description string `json:"Description"`
    Amount      interface{} `json:"Amount"`
}

func (c Cart) GetAmount() (float64,error) {
  if d, ok:=c.Amount.(float64); ok {
     return d,nil
  }
  if s, ok:=c.Amount.(string); ok {
     return strconv.ParseFloat(s,64)
  }
  return 0, errors.New("Invalid amount")
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>