json - Unmarshal _id to id wont work -


so structure looks this:

type article struct {     id bson.objectid `json:"id" bson:"_id,omitempty"`     langcode string `json:"langcode" bson:"langcode"`     authorid string `json:"authorid" bson:"authorid"`     authorname string `json:"authorname" bson:"authorname"`     articletype int64 `json:"type" bson:"type"`     title string `json:"title" bson:"title"`     intro string `json:"intro" bson:"intro"`     body string `json:"body" bson:"body"`     mainpic string `json:"mainpic" bson:"mainpic"`     tags string `json:"tags" bson:"tags"`     slug string `json:"slug" bson:"slug"`     dateadded time.time `json:"dateadded" bson:"dateadded"`     status int64 `json:"status" bson:"status"` } 

and following snippet:

pagereturn.pagination = resultslist.pagination err = json.unmarshal(resultslist.results, &pagereturn.articles) 

will return data without value _id database (i mean in json string id equal "")

if change id bson.objectid json:"id" bson:"_id,omitempty" id bson.objectid json:"_id" bson:"_id,omitempty"

value returned (actual _id value db returned)

i'm wondering how can avoid (but still need use json.unmarshal)

  • unmarshal article struct, tag json:"_id"
  • two struct types differ tags can converted each other. 1 solution create articlebis type, tag json:"id" instead. convert article articlebis instance, marshal.

another simple example:

package main  import "fmt" import "encoding/json"  type base struct {     firstname string `json:"first"` }  type struct {     base     lastname string `json:"last"` }  type b struct {     base     lastname string `json:"lastname"` }  func main() {     john := a{base: base{firstname: "john"}, lastname:"doe"}     john1 := b(john)     john_json, _ := json.marshal(john)     john1_json, _ := json.marshal(john1)     fmt.println(string(john_json))     fmt.println(string(john1_json)) } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -