Go – constructing struct/json on the fly

huangapple go评论87阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年5月7日 23:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/30105798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定