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

时间:2019-06-18 09:35:58

标签: json mongodb go bson

我想将mongo-go-driver中的bson有效地转换为json。

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

例如,我想将下面的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
}

1 个答案:

答案 0 :(得分:2)

如果您知道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转换为类型(可能是如上所述的自定义类型)