go - golang unmarshal a json object into map[string]interface{} by default, how can I unmarshal it to []byte? -
golang unmarshal json object map[string]interface{} default, how can unmarshal []byte? because need secondary unmarshal struct instance after got type.
why don't unmarshal json
struct directly?
or in case have more objects slice of struct?
package main import ( "encoding/json" "fmt" ) type testjson struct { foo string baz string } var ( jsonvalue = `{"foo" : "bar", "baz" : "qux"}` jsonvalueslice = `[{"foo" : "bar", "baz" : "qux"},{"foo" : "second bar", "baz" : "second qux"}]` ) func main() { t := testjson{} err := json.unmarshal([]byte(jsonvalue), &t) if err != nil { fmt.println(err) } fmt.printf("%+v\n", t) t2 := []testjson{} err2 := json.unmarshal([]byte(jsonvalueslice), &t2) if err2 != nil { fmt.println(err2) } fmt.printf("%+v\n", t2) }
edit : go doesn't unmarshal map[string]interface{} default, read docs!
func unmarshal(data []byte, v interface{}) error
golang json.unmarshal can populate anyting, long data consistant.
Comments
Post a Comment