当前位置: > > > > go json marshal 的默认大小写选项?
来源:stackoverflow
2024-04-28 12:00:34
0浏览
收藏
今天将给大家带来《go json marshal 的默认大小写选项?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
问题内容
我有以下结构要导出到 json:
type ExportedIncident struct { Title string `json:"title"` Host string `json:"host"` Status string `json:"status"` Date string `json:"date"` Notes []ExportedNote `json:"notes"` LogEntries []ExportedLogEntry `json:"log_entries"` }
而且我想要下划线大小写字段,因此我必须为此答案中所述定义每个字段:https://stackoverflow.com/a/11694255/1731473
但这确实很麻烦,我相信go中有一个更简单的解决方案,但我找不到它。
如何为 json 导出设置默认字母大小写(下划线、蛇形、驼峰…)?
解决方案
不幸的是,没有机会将您的字段导出到 snake_case
,因此您必须自己维护标签。
从技术上讲,您可以使用方法 marshaljson
并在该方法内执行所有操作,但这并不是更简单的方法…
正如 @vladimir kovpak 所提到的,您不能使用标准来执行此操作图书馆,至少目前是这样。
不过,受到 的启发,您可以实现一些接近您想做的事情。查看 marshalindentsnakecase
:
func MarshalIndentSnakeCase(v interface{}, prefix, indent string) ([]byte, error) { b, err := json.MarshalIndent(v, prefix, indent) if err != nil { return nil, err } x := convertKeys(b) // Here convert all keys from CamelCase to snake_case buf := &bytes.Buffer{} err = json.Indent(buf, []byte(x), prefix, indent) if err != nil { return nil, err } return buf.Bytes(), nil }
缺点:
- 您必须在相反的方向上执行相同的操作才能使 unmashalling 正常工作。
- 由于在
convertkeys()
中使用map
,元素顺序丢失。
拨打 试试。
终于介绍完啦!小伙伴们,这篇关于《go json marshal 的默认大小写选项?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~公众号也会发布Golang相关知识,快来关注吧!