json - 在 Go 中解码时输入检查 json 值

标签 json go

我正在使用通常提供 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 type:它接受 JSON 数字和 JSON 字符串,如果它以字符串形式给出,它可以“自动”解析数字 Number.Int64() Number.Float64() .不需要自定义编码器/解码器。

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}

关于json - 在 Go 中解码时输入检查 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64040825/

相关文章:

javascript - 如何使用jquery解析json字符串

python - pandas Dataframe 到 JSON 字典列表

reactjs - 在 Go 中从 Back 发送 Cookie,这是一个 api 休息,使用 React JS 发送到前端

unit-testing - 将 POST 变量添加到 Go 测试 http 请求

c# - 从 json 文件制作动态字典

MySQL JSON_OBJECT() 一些字段已经包含 JSON 字符串

c++ - QT 读取 JSON 文件并存储和检索值

go - 如何停止 http.ListenAndServe()

go - 如何确保 NoSQL 记录中属性的唯一性(Golang + tiedot)

go - 如何从 LoRa App 服务器接收数据?