去 - 即时构建结构/json



在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)

有时只需在一个地方而其他地方就需要具有特定模式(类型声明)的对象(struct)。我不想产生许多无用的类型,也不想为此使用反射。

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)

最新更新