我正在工作中编写一个 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/