繁体   English   中英

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

[英]How to get data as is from MongoDB and send it to an API as JSON in Golang

I am writing a Golang API at work which when called, gets data from two different MongoDB Collections and appends it into a struct, converts it to JSON, and stringified and sends to an 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 时,而不是在 JSON 中编码为"fookey":"barvalue" ,它被编码为"Key":"fookey","Value":"barvalue" ,如何避免这种行为并将其设置为"fookey":"barvalue"

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM