简体   繁体   English

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

[英]Default case option for go json marshal?

I have the following structures to export onto json: 我具有以下要导出到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"`
}

And I want underscore cased fields, so I had to define each field just for that as described in this answer: https://stackoverflow.com/a/11694255/1731473 而且我想在下划线的情况下使用下划线字段,因此我只需要为此字段定义每个字段,如此答案中所述: https : //stackoverflow.com/a/11694255/1731473

But it's really cumbersome and I believe there is a simpler solution in Go, but I can't find it. 但这确实很麻烦,我相信Go中有一个更简单的解决方案,但我找不到。

How can I set default letter-case (underscore, snake, camel...) for JSON export? 如何为JSON导出设置默认字母大小写(下划线,蛇形,驼色...)?

Unfortunately there are no opportunities to export your fields into snake_case so you have to maintain tags by yourself. 不幸的是,没有机会将您的字段导出到snake_case因此您必须自己维护标签。

Technically you can use method MarshalJSON and perform all manipulations inside this method, but it isn't easier way... 从技术上讲,您可以使用MarshalJSON方法并在此方法内执行所有操作,但这并不是更简单的方法...

As mentioned by @Vladimir Kovpak, you can't do this with the standard library, at least at the moment. 正如@Vladimir Kovpak所提到的,至少在目前,您无法使用标准库执行此操作。


Though, inspired by this , you can achieve something close to what you want to do. 虽然,启发 ,就可以实现了接近你想要做什么。 Check out MarshalIndentSnakeCase : 看看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
}

Down Sides: 缺点:

  • You have to do the same in the opposite direction for Unmashalling to work. 为了使Unmashalling正常工作,您必须在相反的方向进行相同的操作。
  • The order of elements is lost due to using a map inside convertKeys() . 由于在convertKeys()内部使用了map ,因此失去了元素的顺序。

Try it on Go Playground . Go Playground上尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM