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

后端 未结 1 1406
无人共我
无人共我 2021-01-17 06:12

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

相关标签:
1条回答
  • 2021-01-17 07:01

    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)

    0 讨论(0)
提交回复
热议问题