Skip to content

Instantly share code, notes, and snippets.

@smagch
Created July 1, 2013 15:07
Show Gist options
  • Select an option

  • Save smagch/5901660 to your computer and use it in GitHub Desktop.

Select an option

Save smagch/5901660 to your computer and use it in GitHub Desktop.
Go JSON manipulation spike
package main
import (
"log"
"encoding/json"
)
type Hoge struct {
Name string `json:"name"`
Body map[string]interface{} `json:"body"`
}
type Foo struct {
Name string `json:"name"`
Body []interface{} `json:"body"`
}
// Simple JSON wrapping test
// I think Go is quite good at manipulating JSON at this point.
// When it need to change some fields, you might wanna use
// https://github.com/bitly/go-simplejson
func main() {
// JSON wrapping test
var h Hoge
b := []byte(`{"id":"0fd34da25b13b","message":"Hello","date":"2012-12-01"}`)
if err := json.Unmarshal(b, &h.Body); err != nil {
panic(err.Error())
}
h.Name = "Tomoya"
log.Println(h)
if hogeJson, err := json.Marshal(&h); err != nil {
panic(err.Error())
} else {
log.Println(string(hogeJson))
}
// JSON(Array) wrapping test
var f Foo
b2 := []byte(`["foo","bar","hoge", {"smagch": "tomoya"}]`)
if err := json.Unmarshal(b2, &f.Body); err != nil {
panic(err.Error())
}
f.Name = "Smagch"
log.Println(f)
if fooJson, err := json.Marshal(&f); err != nil {
panic(err.Error())
} else {
log.Println(string(fooJson))
}
}
@smagch
Copy link
Copy Markdown
Author

smagch commented Jul 2, 2013

Probably, it's better to use RawMessage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment