Created
July 1, 2013 15:07
-
-
Save smagch/5901660 to your computer and use it in GitHub Desktop.
Go JSON manipulation spike
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably, it's better to use RawMessage.