英文:
Go - constructing struct/json on the fly
问题
在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, _ := json.Marshal(example)
有时候我们只需要在一个特定的地方使用具有特定模式(类型声明)的对象(结构体),而不需要在其他地方使用。我不想生成大量无用的类型,也不想使用反射来实现这一点。
在Go语言中是否有任何语法糖可以提供更优雅的方式来做到这一点?
英文:
In Python it is possible to create a dictionary and serialize it as a JSON object like this:
example = { "key1" : 123, "key2" : "value2" }
js = json.dumps(example)
Go is statically typed, so we have to declare the object schema first:
type Example struct {
Key1 int
Key2 string
}
example := &Example { Key1 : 123, Key2 : "value2" }
js, _ := json.Marshal(example)
Sometimes object (struct) with a specific schema (type declaration) is needed just in one place and nowhere else. I don't want to spawn numerous useless types, and I don't want to use reflection for this.
Is there any syntactic sugar in Go that provides a more elegant way to do this?
答案1
得分: 22
你可以使用一个map:
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"})
}
英文:
You can use a map:
example := map[string]interface{}{ "Key1": 123, "Key2": "value2" }
js, _ := json.Marshal(example)
You can also create types inside of a function:
func f() {
type Example struct { }
}
Or create unnamed types:
func f() {
json.Marshal(struct { Key1 int; Key2 string }{123, "value2"})
}
答案2
得分: 19
你可以使用匿名结构体类型。
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)
英文:
You could use an anonymous struct type.
example := struct {
Key1 int
Key2 string
}{
Key1: 123,
Key2: "value2",
}
js, err := json.Marshal(&example)
Or, if you are ready to lose some type safety, map[string]interface{}
:
example := map[string]interface{}{
"Key1": 123,
"Key2": "value2",
}
js, err := json.Marshal(example)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论