serialization - Encoding nested JSON in Go -



serialization - Encoding nested JSON in Go -

i've had lot of problem finding illustration of this. of info on net decoding json.

i'd serialize info nested json, example:

{ "item": { "title": "items", "properties": [ { "num": 1, "name": "item 1" }, { "num": 2, "name": "item 2" } ] } }

i know how marshal info flat struct, how set info struct can serialized nesting?

http://play.golang.org/p/ndkmv1mytd

i found tool generates struct json schema, don't understand how info sub structs.

http://mholt.github.io/json-to-go/

type illustration struct { item struct { title string `json:"title"` properties []struct { num int `json:"num"` name string `json:"name"` } `json:"properties"` } `json:"item"` }

this tool found nice, not utilize it. makes hard initialize structs.

init illustration snippet: (http://play.golang.org/p/_qw3qp8xzh)

package main import ( "encoding/json" "fmt" ) type illustration struct { item struct { title string `json:"title"` properties []struct { num int `json:"num"` name string `json:"name"` } `json:"properties"` } `json:"item"` } func main() { info := &example{ item: struct { title string `json:"title"` properties []struct { num int `json:"num"` name string `json:"name"` } `json:"properties"` }{ title: "title", properties: []struct { num int `json:"num"` name string `json:"name"` }{ {num: 0, name: "name0"}, {num: 1, name: "name1"}, }, }, } b, err := json.marshal(info) if err != nil { fmt.println(err) homecoming } fmt.println(string(b)) }

result (pretty printed):

{ "item": { "title": "title", "properties": [ { "num": 0, "name": "name0" }, { "num": 1, "name": "name1" } ] } }

i think improve utilize named struct vs anonymous nested ones.

same illustration named structs: http://play.golang.org/p/xm7bxxegtc

package main import ( "encoding/json" "fmt" ) type illustration struct { item item `json:"item"` } type item struct { title string `json:"title"` properties []property `json:"properties"` } type property struct { num int `json:"num"` name string `json:"name"` } func main() { info := &example{ item: item{ title: "title", properties: []property{ {num: 0, name: "name0"}, {num: 1, name: "name1"}, }, }, } b, err := json.marshal(info) if err != nil { fmt.println(err) homecoming } fmt.println(string(b)) }

it exact same thing, find more clear , easy use.

json serialization encoding go

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -