json - 如何从 MongoDB 获取数据并将其作为 Golang 中的 JSON 发送到 API

标签 json mongodb go struct bson

我正在工作中编写一个 Golang API,当调用该 API 时,它会从两个不同的 MongoDB 集合获取数据并将其附加到结构中,将其转换为 JSON,然后进行字符串化并发送到 API (Amazon SQS)

问题是,定义从 MongoDB 接收的数据的结构,虽然有些字段定义正确,但有些字段不同

// IncentiveRule struct defines the structure of Incentive rule from Mongo
type IncentiveRule struct {
    ... Other vars
    Rule               Rule               `bson:"rule" json:"rule"`
    ... Other vars
}

// Rule defines the struct for Rule Object inside an incentive rule
type Rule struct {
    ...
    Rules          interface{}    `bson:"rules" json:"rules"`
    RuleFilter     RuleFilter     `bson:"rule_filter" bson:"rule_filter"`
    ...
}

// RuleFilter ...
type RuleFilter struct {
    Condition string        `bson:"condition" json:"condition"`
    Rules     []interface{} `bson:"rules" json:"rules"`
}

虽然这有效,但 Rule 结构中定义的 interface{} 是变化的,同时获取为 BSON 并解码并重新编码为 JSON,而不是编码为 "fookey":"barvalue" 在 JSON 中,它被编码为 "Key":"fookey","Value":"barvalue",如何避免这种行为并有它为 "fookey":"barvalue"

最佳答案

如果您使用 interface{},mongo-go 驱动程序可以自由选择它认为适合表示结果的任何实现。通常它会选择bson.D表示文档,它是键值对的有序列表,其中键值对是一个具有 Key 字段和 Value 字段的结构体,因此 Go 值可以保留字段顺序。

如果字段顺序不是必需的/不重要的,您可以明确使用 bson.M 而不是 interface{}[]bson.M 而不是 []interface{}bson.M是一个无序映射,但它以 fieldName: fieldValue 的形式表示字段,这正是您想要的。

关于json - 如何从 MongoDB 获取数据并将其作为 Golang 中的 JSON 发送到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453773/

相关文章:

javascript - 在javascript中使用变量的值来访问JSON对象

json - 如何在时代更新 Postgres 中的当前时间的 json 对象

mongodb - MongoDB 中 "Parent Links"树上的 MapReduce

docker - go get golang-migrate inside of docker 错误

Golang 多个 goroutine 通过引用共享同一个变量

javascript - jQuery/JS : Sorting array based upon another array?

JSON 对象的 MySQL 聚合总和

python - 如何从 python 中使用 mongolab 附加组件到 Heroku?

python - 使用 PyMongo 获取按发布日期降序排列的不同值

templates - 如何将变量传递给模板并在 beego 中接收变量