How to define multiple name tags in a struct

JsonStructGo

Json Problem Overview


I need to get an item from a mongo database, so I defined a struct like this

type Page struct {
    PageId string                 `bson:"pageId"`
    Meta   map[string]interface{} `bson:"meta"`
}

Now I also need to encode it to JSON, but it encodes the fields as uppercase (i get PageId instead of pageId) so i also need to define field tags for JSON. I tried something like this but it didn't work:

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`
}

So how can this be done, define multiple name tags in a struct?

Json Solutions


Solution 1 - Json

What you need to do is to use space instead of commas as tag string separators.

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"meta"`
}

It says in the documentation of the reflect package:

> By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

Solution 2 - Json

Thanks for the accepted answer.

Below is just for the lazy people like me.

INCORRECT

type Page struct {
    PageId string                 `bson:"pageId",json:"pageId"`
    Meta   map[string]interface{} `bson:"meta",json:"pageId"`
}

CORRECT

type Page struct {
    PageId string                 `bson:"pageId" json:"pageId"`
    Meta   map[string]interface{} `bson:"meta" json:"pageId"`
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsccView Question on Stackoverflow
Solution 1 - JsonANisusView Answer on Stackoverflow
Solution 2 - JsonBennyView Answer on Stackoverflow