简体   繁体   English

用 sql.NullFloat64 包装 json.Number

[英]Go wrapping json.Number with sql.NullFloat64

I'm working with an API that has json values that can be a number or string and can sometimes be an empty string.我正在使用具有 json 值的 API,该值可以是数字或字符串,有时可以是空字符串。 For example:例如:

[
    {
        "Description": "Doorknob",
        "Amount": 3.25
    },
    {
        "Description": "Light bulb",
        "Amount": "4.70"
    },
    {
        "Description": "Screwdriver",
        "Amount": ""
    }
]

I've learned I can use json.Number to deal with cases where the value can be a number or a string.我了解到我可以使用 json.Number 来处理值可以是数字或字符串的情况。 But how do I deal with the cases where it's an empty string?但是我如何处理它是一个空字符串的情况?

I need to insert these values into a postgres database so I'd like cases where it's an empty string to show as null and I'm thinking sql.NullFloat64 would be best suited to handle it.我需要将这些值插入到 postgres 数据库中,因此我希望将空字符串显示为null ,我认为 sql.NullFloat64 最适合处理它。

Here's a function I'm using that works on the first 2 cases (Doorknob and Light bulb), but fails to unmarshal the last ("Screwdriver").这是我正在使用的一个函数,它适用于前两种情况(门把手和灯泡),但无法解组最后一种情况(“螺丝刀”)。

Here is an unmarshaling function I'm trying to use, but I can't figure out why it's not working:这是我正在尝试使用的解组函数,但我不知道为什么它不起作用:

type NullNumber struct{ sql.NullFloat64 }

func (nn *NullNumber) UnmarshalJSON(data []byte) error {
    var x *json.Number
    if err := json.Unmarshal(data, &x); err != nil {
        return err
    }
    if len(*x) == 0 {
        nn.Valid = false // This doesn't seem to be working. Why?
    }
    this, err := x.Float64()
    if err != nil {
        return err
    }
    nn.Valid = true
    nn.Float64 = this
    return nil
}

Is this a case where I should be using an open interface for the amount?在这种情况下,我应该为金额使用开放式界面吗?

Any help is very appreciated.非常感谢任何帮助。

playground: https://play.golang.org/p/QYQRq94OtV3游乐场: https : //play.golang.org/p/QYQRq94OtV3

You're almost there!您快到了! json.Unmarshal call errors when a json.Number is given an empty string.当给json.Number一个空字符串时, json.Unmarshal调用错误。

Add this check beforehand:预先添加此检查:

// edge case: json.Number is given an empty string
if bytes.Equal(data, []byte(`""`)) {
    nn.Valid = false
    return nil
}

https://play.golang.org/p/ILxC8tjYI_G https://play.golang.org/p/ILxC8tjYI_G

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM