Go-动态构造struct/json
在Python中,可以创建字典并将其序列化为JSON对象,如下所示:Go-动态构造struct/json,json,go,syntactic-sugar,Json,Go,Syntactic Sugar,在Python中,可以创建字典并将其序列化为JSON对象,如下所示: example = { "key1" : 123, "key2" : "value2" } js = json.dumps(example) Go是静态类型的,因此我们必须首先声明对象架构: type Example struct { Key1 int Key2 string } example := &Example { Key1 : 123, Key2 : "value2" } js, _ :=
example = { "key1" : 123, "key2" : "value2" }
js = json.dumps(example)
Go是静态类型的,因此我们必须首先声明对象架构:
type Example struct {
Key1 int
Key2 string
}
example := &Example { Key1 : 123, Key2 : "value2" }
js, _ := json.Marshal(example)
有时,只需要在一个地方使用具有特定模式(类型声明)的对象(结构),而不需要在其他地方使用。我不想产生大量无用的类型,也不想为此使用反射
围棋中是否有语法上的糖分可以提供一种更优雅的方式来实现这一点 您可以使用地图:
example := map[string]interface{}{ "Key1": 123, "Key2": "value2" }
js, _ := json.Marshal(example)
还可以在函数内部创建类型:
func f() {
type Example struct { }
}
或创建未命名的类型:
func f() {
json.Marshal(struct { Key1 int; Key2 string }{123, "value2"})
}
您可以使用匿名结构类型
example := struct {
Key1 int
Key2 string
}{
Key1: 123,
Key2: "value2",
}
js, err := json.Marshal(&example)
或者,如果您准备丢失某些类型安全性,map[string]interface{}
:
example := map[string]interface{}{
"Key1": 123,
"Key2": "value2",
}
js, err := json.Marshal(example)