How to convert bson to json effectively with mongo-go-driver?

别来无恙 提交于 2020-07-15 10:03:16

问题


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

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

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?

The below fails.

// 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:


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"`
    /* ... */
}

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)



来源:https://stackoverflow.com/questions/56646062/how-to-convert-bson-to-json-effectively-with-mongo-go-driver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!