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

问题描述 投票:1回答:1

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

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

json mongodb go struct bson
1个回答
1
投票

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

如果不需要/重要的字段顺序,则可以显式使用Value代替bson.M,并使用interface{}代替[]bson.M[]interface{}是无序映射,但是它以bson.M的形式表示字段,这正是您想要的。

© www.soinside.com 2019 - 2024. All rights reserved.