如何使用mongo-go-driver有效地将bson转换为json? [英] How to convert bson to json effectively with mongo-go-driver?

查看:103
本文介绍了如何使用mongo-go-driver有效地将bson转换为json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to convert bson in mongo-go-driver to json effectively.

我应该小心处理 NaN ,因为 json.Marshal NaN ,则$ c>失败。

I should take care to handle NaN, because json.Marshal fail if NaN exists in data.

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

For instance, I want to convert below bson data to 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 json.Unmarshaler 接口的自定义类型,并根据需要处理NaN。例如:

If you know the structure if your BSON, you can create a custom type that implements the json.Marshaler and json.Unmarshaler interfaces, and handles NaN as you wish. Example:

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

If you have an arbitrary structure of your BSON, your only option is to traverse the structure, using reflection, and convert any occurrences of NaN into a type (possibly a custom type as described above)

这篇关于如何使用mongo-go-driver有效地将bson转换为json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆