Soullivaneuh
Soullivaneuh

Reputation: 3863

Default case option for go json marshal?

I have the following structures to export onto 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

But it's really cumbersome and I believe there is a simpler solution in Go, but I can't find it.

How can I set default letter-case (underscore, snake, camel...) for JSON export?

Upvotes: 3

Views: 4102

Answers (2)

cn0047
cn0047

Reputation: 17091

Unfortunately there are no opportunities to export your fields into snake_case so you have to maintain tags by yourself.

Technically you can use method MarshalJSON and perform all manipulations inside this method, but it isn't easier way...

Upvotes: 1

ifnotak
ifnotak

Reputation: 4662

As mentioned by @Vladimir Kovpak, you can't do this with the standard library, at least at the moment.


Though, inspired by this, you can achieve something close to what you want to do. Check out 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.
  • The order of elements is lost due to using a map inside convertKeys().

Try it on Go Playground.

Upvotes: 1

Related Questions