Skip to content

Instantly share code, notes, and snippets.

@smahs
Last active August 29, 2015 14:25
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 smahs/e3a283efdaf4aa32aeae to your computer and use it in GitHub Desktop.
Save smahs/e3a283efdaf4aa32aeae to your computer and use it in GitHub Desktop.
Generate a hashmap from a struct (without reflection magic), and then merge it with another map and return a merged json.
/* The last I checked, this gist can be run at:
http://play.golang.org/p/5keNQZLqfR
*/
package main
import (
"fmt"
"encoding/json"
)
type This struct {
a int
b string
}
func (t This) getMap() *map[string]interface{} {
return &map[string]interface{} {
"a": t.a,
"b": t.b,
}
}
func (t This) merge(extra *map[string]interface{}) ([]byte, error) {
this := *t.getMap()
for i := range *extra {
this[i] = (*extra)[i]
}
return json.Marshal(this)
}
func main() {
t := This{1, "@"}
merged, _ := t.merge(&map[string]interface {}{"c": "blah"})
fmt.Println(string(merged))
}
/* Prints:
{"a":1,"b":"@","c":"blah"}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment