Udaya Prakash
Udaya Prakash

Reputation: 541

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)

The problem is, defining the struct of the data receiving from MongoDB, while some of the fields are defined properly, some are varying

// 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"`
}

While this works, the interface{} defined inside Rule struct is varying and while getting as BSON and decoding and re-encoding to JSON, instead of encoding as "fookey":"barvalue" in JSON, it is encoded as "Key":"fookey","Value":"barvalue", how to avoid this behavior and have it as "fookey":"barvalue"

Upvotes: 2

Views: 372

Answers (1)

icza
icza

Reputation: 417622

If you use interface{}, the mongo-go driver is free to choose whatever implementation it sees fits for representing the results. Often it will choose bson.D to represent documents which is an ordered list of key-value pairs where a pair is a struct having a field for Key and a field for Value , so the Go value can preserve the field order.

If field order is not required / important, you may explicitly use bson.M instead of interface{} and []bson.M instead of []interface{}. bson.M is an unordered map, but it represents fields in the form of fieldName: fieldValue, which is exactly what you want.

Upvotes: 2

Related Questions