gpt4 book ai didi

json - Go - 即时构建 struct/json

转载 作者:IT王子 更新时间:2023-10-29 01:09:58 24 4
gpt4 key购买 nike

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

最佳答案

您可以使用 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"})
}

关于json - Go - 即时构建 struct/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30105798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com