0

When I take my grab a post form my db and try and render it to JSON I run into some problems:

type PostBSON struct {
  Id      bson.ObjectId `bson:"_id,omitempty"`
  Title   string        `bson:"title"`
}

// ...

postBSON := PostBSON{}
id := bson.ObjectIdHex(postJSON.Id)
err = c.Find(bson.M{"_id": id}).One(&postBSON)

// ...

response, err := bson.MarshalJSON(postBSON)

The MarshalJSON doesn't handle hexing Id (ObjectId) for me . Thus I get:

{"Id":{"$oid":"5a1f65646d4864a967028cce"}, "Title": "blah"}

What is the correct way to clean up the output?

{"Id":"5a1f65646d4864a967028cce", "Title": "blah"}

Edit: I wrote my own stringify as described here. Is this a performant solution? And is it idiotmatic go?

func (p PostBSON) String() string {
  return fmt.Sprintf(`
        {
          "_id": "%s",
          "title": "%s",
          "content": "%s",
          "created": "%s"
        }`,
    p.Id.Hex(),
    p.Title,
    p.Content,
    p.Id.Time(),
  )
Ashley Coolman
  • 11,095
  • 5
  • 59
  • 81

1 Answers1

2

You can implement a MarshalJSON to satisfy json.Marshaler interface, e.g.:

func (a PostBSON) MarshalJSON() ([]byte, error) {
    m := map[string]interface{}{
        "id": a.Id.Hex(),
        "title": a.Title,
    }
    return json.Marshal(m)
}
hsrv
  • 1,372
  • 10
  • 22