通过 map 生成 json,告别 struct 困扰
对于 go 新手来说,生成 json 时,似乎只能通过 struct 来实现,这无疑会带来一些不便。尤其是在处理复杂或多样的 json 结构时,定义大量的 struct 体会让人感到繁琐。
map[string]interface{} 你的救星
其实,go 提供了另一种生成 json 的方式,既灵活又方便——map[string]interface{}.
b, _ := json.Marshal(map[string]interface{}{ "a": "aa", "b": "bb", "c": "cc", "d": "dd", })
通过使用 map,你可以轻松地添加、修改或删除 json 中的字段,而无需定义任何 struct 体。json.marshal 函数会自动将 map 转换为 json 字符串。
优点一览
因此,如果你需要生成复杂或多样的 json,不妨尝试使用 map[string]interface{},它将大大简化你的编码过程。