json - Go - 即时构建 struct/json

标签 json go syntactic-sugar

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

相关文章:

javascript - 如果在数组中发现重复项,必须通过纯 javascript 添加带有键的索引

go - 用函数查找字符串

go - 如何使用 SeekToLast 获取最后一个键值

go - 用go写的好的CMS是什么?

c++ - 使用 Rcpp 糖就地修改 SEXP

python - 如何将 pandas DataFrame 的列解压为多个变量

scala - Scala 的 apply() 方法魔法是如何工作的?

json - Swift - 将 [[String :Any? ]] 转换为数据

javascript - 从 json 构建 Promise 流程

sql - Postgresql:将列子集和子查询结果组装成 JSON 文档