I had some complex JSON to deserialize into Go structs and a matching JSON schema file. The JSON schema is likely to change a lot over the next few weeks, so I wondered “Is there was a way to create the Go structs automatically based on the JSON schema?”
I searched github.com and found a bunch of packages in various states, so I put together a cut-down version of my app’s schema and tried it out.
Failed to work out of the box at all on my test schema. Issue raised: https://github.com/interagent/schematic/issues/36
./schematic ~/goprojects/src/github.com/a-h/schemagenerators/exampleschema.json schematic: 12:5: expected 'IDENT', found 'import'
Produced some workable-ish Go code. I was expecting the type “Example” to have properties for name, status and address, but it didn’t. Either way there are no unit tests so if it does work, it’s partly by luck.
Looks OK, but relies on some more packages from the author to do with bin-data which I don’t think should be required. Maybe this is for personal use?
OK, it’s got a beta warning and no unit tests. Let’s do this.
Sadly, it doesn’t compile right now, left an issue, got a nice message from the author.
Needs some stuff that runs from https://bitbucket.org/pkg/inflect, couldn’t be bothered installing the Mercurial tools.
OK, so after this, I got bored and decided to fix the bug in schematic because it has unit tests. The problem was actually with go format on the code that it produces:
Once I’d fixed that, I got this code out of it, but it still lacked expected properties for the example type – name, address and status.
Argh – I’m writing my own
So, I decided to write something that does what I need over at https://github.com/a-h/generate
While I haven’t tested all of the JSON schema features (just the ones I need), it’s reasonably well unit tested and produces the output I was looking for:
I’ll be using it to work on a system over the next few weeks, so it’s likely to evolve. Ping me if you find it useful!