json - 如何使用 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
}
解决方案
如果您知道 BSON 的结构,则可以创建一个自定义类型来实现json.Marshaler
和json.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 转换为类型(可能是如上所述的自定义类型)
推荐阅读
- c++ - 带有输出选择器的 Gstreamer 管道无法启动
- php - 如何在sql中按两列分组?
- php - Typo3 8.7.x / Typoscript:无法从 rootpage 获取数据,在 rootpage 之前滑动停止
- angular - 我可以像这样声明基于 json 格式的 TypeScript 对象吗?
- ios - 如何通过 callkit 在 iOS 上结束通话?
- javascript - 如何在 Angular 6 中使用 JQuery.flowchart
- python - 在 Python 中将多个 CSV 文件合并到电子表格的单独选项卡中
- wordpress - WordPress 编辑器中的最少字符数
- php - 返回在哪个表中找到该项目
- php - 在 woocommerce 管理产品列表中为产品标签添加过滤器下拉列表