How to define multiple name tags in a structure

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

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

Now I also need to encode it in 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 this did not work:

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

So, how can this be done by defining several name tags in the structure?

+100
json struct go
05 Sep '13 at 11:56 on
source share
2 answers

The documentation for the reflect package says:

By convention, tag lines represent the concatenation of keys optionally separated by spaces: value pairs. Each key is a non-empty string consisting of uncontrolled characters other than space (U + 0020 ''), quote (U + 0022 '' ') and a colon (U + 003A': '). Each value is quoted using the characters U + 0022 '' 'and Go string literal.

What you need to do is use space instead of a comma as a line separator for the tag.

 type Page struct { PageId string 'bson:"pageId" json:"pageId"' Meta map[string]interface{} 'bson:"meta" json:"meta"' } 
+163
Sep 05 '13 at 12:07 on
source share

Thanks for the accepted answer.

The following are only for lazy people like me.

WRONG

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

RIGHT

 type Page struct { PageId string `bson:"pageId" json:"pageId"` Meta map[string]interface{} `bson:"meta" json:"pageId"` } 
+53
Jun 04 '15 at 10:18
source share



All Articles