英文:
Store struct as string in redis
问题
Redis只能存储字符串,我想知道如何在Go语言中实现类似于JavaScript的JSON.stringify的功能,将结构体转换为字符串。
我尝试了类型转换:
string(结构体)
但是这会导致错误。
英文:
As Redis only stores strings I would like to know how I can do the equivalent of Javascript's JSON.stringify using Go to convert a Struct into a string.
I have tried typecasting:
string(the_struct)
but this results in an error.
答案1
得分: 0
encoding/json
包可以用于将 struct
转换为 JSON 字符串,反之亦然(将 JSON 字符串解析为 struct
)。
简单示例(在 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 -> Struct
var p2 Person
err = json.Unmarshal(data, &p2)
if err != nil {
panic(err)
}
fmt.Printf("%+v", p2)
}
输出:
{"Name":"Bob","Age":23}
{Name:Bob Age:23}
注意事项:###
struct
的字段必须是公开的(以大写字母开头),否则 json
包(使用反射)将无法读取/写入它们。
您还可以为结构字段指定标签,以控制/微调 JSON 编组/解组过程,例如更改 JSON 文本中的名称:
type Person struct {
Name string `json:"name"`
Age int `json:"years"`
}
通过这个更改,上述应用程序的输出如下:
{"name":"Bob","years":23}
{Name:Bob Age:23}
json.Marshal()
函数的文档详细介绍了标签提供的可能性。
通过实现 json.Marshaler
和 json.Unmarshaler
接口,您可以完全自定义编组/解组过程。
此外,如果您的结构体没有预定义(例如,您事先不知道字段),可以使用 map[string]interface{}
。请参阅此答案以获取详细信息和示例。
英文:
The encoding/json
package can be used to easily convert a struct
to JSON string and vice versa (parse a JSON string into a struct
).
Simple example (try it on the 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 the struct
must be exported (start them with capital letter), else the json
package (which uses reflection) will not be able to read/write them.
You can also specify tags for the struct fields to control/fine tune the json marshaling/unmarshaling process, for example to change the names in the JSON text:
type Person struct {
Name string `json:"name"`
Age int `json:"years"`
}
With this change the output of the above application is the following:
{"name":"Bob","years":23}
{Name:Bob Age:23}
The documentation of the json.Marshal()
function details the possibilities provided by the tags.
And by implementing the json.Marshaler
and json.Unmarshaler
interfaces you can fully customize the marshaling / unmarshaling process.
Also if your struct is not pre-defined (e.g. you don't know the fields in advance), you can use a map[string]interface{}
. See this answer for details and examples.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论