首页 > 解决方案 > 如何使用 mongo-go-driver 有效地将 bson 转换为 json?

问题描述

我想有效地将​​ mongo-go-driver中的 bson 转换为 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
}

标签: jsonmongodbgobson

解决方案


如果您知道 BSON 的结构,则可以创建一个自定义类型来实现json.Marshalerjson.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 转换为类型(可能是如上所述的自定义类型)


推荐阅读