json - Store struct as string in redis -
as redis stores strings know how can equivalent of javascript's json.stringify using go convert struct string.
i have tried typecasting:
string(the_struct)
but results in error.
the encoding/json
package can used convert struct
json string , vice versa (parse json string struct
).
simple example (try on go playground):
type person struct { name string age int } func main() { p := person{"bob", 23} // struct -> json data, err := json.marshal(&p) if err != nil { panic(err) } fmt.println(string(data)) // json -> json var p2 person err = json.unmarshal(data, &p2) if err != nil { panic(err) } fmt.printf("%+v", p2) }
output:
{"name":"bob","age":23} {name:bob age:23}
notes:
the fields of struct
must exported (start them capital letter), else json
package (which uses reflection) not able read/write them.
you can specify tags struct fields control/fine tune json marshaling/unmarshaling process, example change names in json text:
type person struct { name string `json:"name"` age int `json:"years"` }
with change output of above application following:
{"name":"bob","years":23} {name:bob age:23}
the documentation of json.marshal()
function details possibilities provided tags.
and implementing json.marshaler
, json.unmarshaler
interfaces can customize marshaling / unmarshaling process.
also if struct not pre-defined (e.g. don't know fields in advance), can use map[string]interface{}
. see answer details , examples.
Comments
Post a Comment