Git Product home page Git Product logo

jsonenums's Introduction

jsonenums

jsonenums is a tool to automate the creation of methods that satisfy the json.Marshaler and json.Unmarshaler interfaces. Given the name of a (signed or unsigned) integer type T that has constants defined, jsonenums will create a new self-contained Go source file implementing

func (t T) MarshalJSON() ([]byte, error)
func (t *T) UnmarshalJSON([]byte) error

The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.

jsonenums is a simple implementation of a concept and the code might not be the most performant or beautiful to read.

For example, given this snippet,

package painkiller

type Pill int

const (
	Placebo Pill = iota
	Aspirin
	Ibuprofen
	Paracetamol
	Acetaminophen = Paracetamol
)

running this command

jsonenums -type=Pill

in the same directory will create the file pill_jsonenums.go, in package painkiller, containing a definition of

func (r Pill) MarshalJSON() ([]byte, error)
func (r *Pill) UnmarshalJSON([]byte) error

MarshalJSON will translate the value of a Pill constant to the []byte representation of the respective constant name, so that the call json.Marshal(painkiller.Aspirin) will return the bytes []byte("\"Aspirin\"").

UnmarshalJSON performs the opposite operation; given the []byte representation of a Pill constant it will change the receiver to equal the corresponding constant. So given []byte("\"Aspirin\"") the receiver will change to Aspirin and the returned error will be nil.

Typically this process would be run using go generate, like this:

//go:generate jsonenums -type=Pill

If multiple constants have the same value, the lexically first matching name will be used (in the example, Acetaminophen will print as "Paracetamol").

With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_jsonenums.go, where t is the lower-cased name of the first type listed. The suffix can be overridden with the -suffix flag and a prefix may be added with the -prefix flag.

This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.

jsonenums's People

Contributors

bpflanz-adfin avatar campoy avatar damnever avatar dmitshur avatar ericwilson29 avatar neurodrone avatar pebers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsonenums's Issues

OmitIfEmpty encoding option issue with documentation

I ran into an issue that was annoying to track down and I'm not sure I entirely get it. I was using jsonenums as part of a nested struct slice, and explicitly setting the json field name & setting the omitifempty flag. My observation was that if I built an instance of that struct explicitly setting the value to be iota 0 as documented in the shirtsize example project, the value during encoding would be removed entirely. If I removed the omitifempty flag, the proper value would show up. Likewise I could also work around it by just adding 1 to the iota const. It may be worth further investigation and/or a simple documentation update to warn people about this.

I was able to track it as far as here in the golang encode library. My gut is telling me somewhere there is a confusion between an iota value of 0 and a nil which is what I expect omitifempty to apply to.

Allow optional list of files to be apart of the package

I've found it useful to access the _TypeNameToValue map in the generated code from other places in my package (probably not best practice), but if I remove the generated file and rerun go generate again it will cause an undeclared name error.

Perhaps it would be useful to allow a list of files as arguments to jsonenums to limit what it parses as apart of the package, i.e. jsonenums -type myType ...files Then we could use a line such as:

//go:generate jsonenums -type=myType $GOFILE

in the file that contains the type declaration.

Flag to allow lowercase values

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?

How to use this library?

Sorry, I really do not know how to use this? I put the //go:generate jsonenums -type=OnlineType in the file. Then I input go generate. It doesn't work. Is there anyone who can teach me?

go1.7: parsing package: ... unknown version: v1

Started getting this after updating to go1.7:

2016/08/18 14:31:01 parsing package: type-checking package: client.go:9:2: could not import io (reading export data: /usr/lib/go/pkg/linux_amd64/io.a: unknown version: v1io'$GOROOT/src/io/io.go*SeekStart*%Seek)

I tried to rebuild jsonenums and update golang.org/x/tools/... but no avail.

Can we assign custom names to enum values ?

type Fruit int
const (
     Apple Fruit = iota
     Banana
     Orange
)

I'd like the strings to be "apple", "banana", "orange". How can I assign custom strings ?

Something like this would work ?

type Fruit int
const (
     Apple Fruit = iota  `"apple"`
     Banana                  `"banana"`
     Orange                  `"orange"`
)

cannot find package "." in:

Hello there!

I don't know if there is still any support but I am having an error:

emixam23@Emixam23-PC:~/xxx$ make regenerate-enums 
jsonenums -type=AccountType xxx/enums.go
2021/09/15 17:19:48 parsing package: provided directory (/home/emixam23/xxx/internal/domain/enums/enums.go) may not under GOPATH (/home/emixam23/xxx): cannot find package "." in:
        /home/emixam23/xxx/internal/domain/enums/enums.go
make: *** [Makefile:59: regenerate-enums] Error 1

It seems like I can't provide a path to the given enums go file

best,

Max

Giving multiple types that all appear in the same file causes duplication in the generated code

//go:generate jsonenums -type=A,B

package main

type A int
const (
   X A = iota
   Y
   Z
)

type B int 
const (
   M B = iota
   N
   O
)

After running "go generate" a_jsonenums.go contains the correct definitions for type A, but b_jsonenums.go has the definitions for both type A and type B.

What I would like best is a way to dump all of the generated json into just one fil like stringer's -o flag allows me to do.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.