如何使用 mongo-go-driver 有效地将 bson 转换为 json?

2024-05-08

我想将 bson 转换为mongo-go 驱动程序 https://github.com/mongodb/mongo-go-driver有效地转换为 json。

我应该小心处理NaN, 因为json.Marshal失败如果NaN存在于数据中。

例如,我想将下面的 bson 数据转换为 json。

b, _ := bson.Marshal(bson.M{"a": []interface{}{math.NaN(), 0, 1}})
// How to convert b to json?

下面失败了。

// decode
var decodedBson bson.M
bson.Unmarshal(b, &decodedBson)
_, err := json.Marshal(decodedBson)
if err != nil {
    panic(err) // it will be invoked
    // panic: json: unsupported value: NaN
}

如果您知道 BSON 的结构,您可以创建一个自定义类型来实现json.Marshaler and json.Unmarshaler接口,并根据需要处理 NaN。例如:

type maybeNaN struct{
    isNan  bool
    number float64
}

func (n maybeNaN) MarshalJSON() ([]byte, error) {
    if n.isNan {
        return []byte("null"), nil // Or whatever you want here
    }
    return json.Marshal(n.number)
}

func (n *maybeNan) UnmarshalJSON(p []byte) error {
    if string(p) == "NaN" {
        n.isNan = true
        return nil
    }
    return json.Unmarshal(p, &n.number)
}

type myStruct struct {
    someNumber maybeNaN `json:"someNumber" bson:"someNumber"`
    /* ... */
}

如果您的 BSON 具有任意结构,则唯一的选择是使用反射遍历该结构,并将任何出现的 NaN 转换为类型(可能是如上所述的自定义类型)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 mongo-go-driver 有效地将 bson 转换为 json? 的相关文章

随机推荐