campoy / jsonenums

This tool is similar to golang.org/x/tools/cmd/stringer but generates MarshalJSON and UnmarshalJSON methods.
Apache License 2.0
490 stars 57 forks source link

Flag to allow lowercase values #13

Closed tv42 closed 7 years ago

tv42 commented 8 years ago

A typical use for me is

const (
    Foo T = iota
    Bar
    Baz
)

but this forces the JSON strings to be "Foo" etc, not "foo", which is not very friendly to the human. Could there be a -lowercase flag or such?

I'm not 100% sure what's the best way to handle CamelCaseWords in general. Should that, with -lowercase, become "camelCaseWords", "camelcasewords", "camel_case_words", or what?

dmitshur commented 8 years ago

but this forces the JSON strings to be "Foo" etc, not "foo", which is not very friendly to the human.

If you don't mind me asking, why do you consider that not friendly?

tv42 commented 8 years ago

@shurcooL Look at most json, or config files in general. Forced upper case is rare. https://en.wikipedia.org/wiki/JSON#Example

kylebrandt commented 8 years ago

I would like a feature similar to this, but instead be able to have alternative value specified in some sort of markup (comments maybe? since there is no such things as iota tags like there are struct tags as far as I know).

The main use case here is making a library for an existing API. A lot of existing non-Go apis will have enum values in the json that are not starting with uppercase and also do not follow naming conventions.

So currently I think I'm limited to using this tool once, and then manually editing the generated file - unless there is a better way?

My current use case:

const (
    Operational         componentStatus = iota // operational
    DegradedPerformance                        // degraded_performance
    PartialOutage                              // partial_outage
    MajorOutage                                // major_outage
)
kylebrandt commented 8 years ago

So I noticed that the generated code will use a stringer interface over the generated Strings based on the iota const name, so I was able to work around this by making my own String() methods that return the json representation (the strings in those comments).

tv42 commented 8 years ago

@kylebrandt One huge problem with MajorOutage // major_outage is that those are docstrings that are visible in godoc. Perhaps just a conversion from CamelCase to snake_case is enough?

THE108 commented 7 years ago

Seems this feature was implemented here -> https://github.com/alvaroloes/enumer/pull/6.

@kylebrandt As far as I know it's not possible to use comments for setting JSON names for enum options because go source code file parsing is based on Stringer (parsing AST).

campoy commented 7 years ago

Thanks for your contribution, but this tool is just a sample. I will not add extra features, just fixes on the current functionality.

campoy commented 7 years ago

(Also sorry for replying to this one year later)