Go - 构建动态结构体/JSON

13
在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中提供更优雅的语法糖来解决这个问题呢?
2个回答

22

你可以使用地图:

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"})
}

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接