Go JSON元帅的默认案例选项?

时间:2019-03-20 10:28:12

标签: json go

我具有以下导出到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导出设置默认的字母大小写(下划线,蛇形,驼色...)?

2 个答案:

答案 0 :(得分:1)

很遗憾,没有机会将您的字段导出到snake_case中,因此您必须自己维护标签。

从技术上讲,您可以使用方法MarshalJSON并在此方法内执行所有操作,但这不是更简单的方法...

答案 1 :(得分:1)

如@Vladimir Kovpak所述,至少在目前,您无法使用标准库来做到这一点。


尽管受到this的启发,但您可以实现接近您想要做的事情。检出TEMPLATES

INSTALLED_APPS

反面:

  • 要使Unmashalling正常工作,您必须朝相反的方向做同样的事情。
  • 由于在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 } ,因此元素的顺序丢失了。

Go Playground上尝试。