Go - 即时构建 struct/json

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 中是否有任何语法糖可以提供更优雅的方式来执行此操作?

您可以使用地图:

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)