Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created November 21, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PyYoshi/70ce944c050f75f40dba to your computer and use it in GitHub Desktop.
Save PyYoshi/70ce944c050f75f40dba to your computer and use it in GitHub Desktop.
Add custom field to JSON in Go
package main
import (
"encoding/json"
"fmt"
"reflect"
)
type D struct {
ID string
Rev string
Doc interface{}
}
func (d D) MarshalJSON() ([]byte, error) {
out := make(map[string]interface{})
dValue := reflect.Indirect(reflect.ValueOf(d.Doc))
dType := dValue.Type()
for i := 0; i < dType.NumField(); i++ {
field := dType.Field(i)
name := dType.Field(i).Name
jsonKey := field.Tag.Get("json")
if jsonKey == "" {
jsonKey = name
}
out[jsonKey] = dValue.FieldByName(name).Interface()
}
out["_id"] = d.ID
out["_rev"] = d.Rev
return json.Marshal(out)
}
type Document struct {
Name string `json:"name"`
}
func main() {
b := Document{}
b.Name = "Bob"
d := D{}
d.ID = "aiueo"
d.Rev = "1-1e895f6f-aa12-4b72-b3d6-9924b6d0678a"
d.Doc = b
jb, err := json.MarshalIndent(&d, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(jb))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment