Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: encoding/json: allow various field style conventions #23027

Closed
gbbr opened this issue Dec 7, 2017 · 2 comments

Comments

Projects
None yet
4 participants
@gbbr
Copy link
Member

commented Dec 7, 2017

Generally JSON APIs allow multiple standard conventions for naming keys, the most common ones in my experience being the snake case and lower camel case. Go provides a bit of a struggle working with these because it uses the less common upper camel case. The work around for this is to augment each field in a struct with the corresponding tag, but that quickly becomes tedious.

My idea would be to allow the encoder/decoder, as well as the global marshaller/unmarshaller to be configured in choosing this standard. Some example code that would go into encoding/json:

type FieldStyle int

const (
    Default FieldStyle = iota
    SnakeCase
    CamelCase
)

Where Default is the current setting with UpperCamelCase. SnakeCase would be the snake_case and CamelCase would be the JavaScript standard camelCase.

Then we could augment the encoder/decoder (and perhaps a global function too) to work in a way similar to:

enc := json.NewEncoder(w).SetFieldStyle(json.CamelCase)
// etc

And so on. Thoughts?

@gopherbot gopherbot added this to the Proposal milestone Dec 7, 2017

@gopherbot gopherbot added the Proposal label Dec 7, 2017

@OneOfOne

This comment has been minimized.

Copy link
Contributor

commented Dec 7, 2017

That's what external tools are for, https://github.com/fatih/gomodifytags comes to mind (which I personally use with both vscode and vim).

@rsc

This comment has been minimized.

Copy link
Contributor

commented Feb 5, 2018

The json package is almost completely done. If you need significantly extended semantics, then it would be fine to copy the current one and make your own modifications, creating a new package customized to your use case.

Or maybe write a tool that adds struct tags to specific structs. I find it hard to believe that forcing a default onto everything in the entire tree of types being encoded is likely to remain correct in large programs.

@rsc rsc closed this Feb 5, 2018

@golang golang locked and limited conversation to collaborators Feb 5, 2019

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
You can’t perform that action at this time.