JSON1 / JSON to Go
JSON to Go
Generate Go structs with JSON tags from a JSON sample. Optional fields become pointers tagged omitempty, so encoding/json can tell absent from the zero value.
Processed locally·Your data never leaves your device
InputJSON
ReadyOutputGo
Converted output appears here as you type.
Good to know
- Every record in an array is inspected, not just the first, so a field that appears in only some of them is typed as optional rather than required.
- Identical nested shapes are emitted once and reused, and reserved words are renamed to something legal in this language.
About this tool
Go structs need a tag on every field to map it to a JSON key, which makes writing them by hand for a large payload slow. This produces the full set, formatted the way gofmt would align them.
Exported names follow Go conventions, including the initialisms the linter expects: an id key becomes ID, not Id.
- Why are some fields pointers?
- Optional fields become pointers tagged
omitempty, which is the only wayencoding/jsoncan tell a field that was absent from one that arrived as the zero value. Without it, a missingcountand acountof 0 are indistinguishable. - Why interface{} instead of any?
anyis an alias forinterface{}added in Go 1.18, so the two are identical to the compiler. The output usesinterface{}because it also compiles on older toolchains, and a struct definition is the last place you want a build to break over a spelling.- How are optional fields decided?
- Every record in an array is inspected, not just the first. A field that appears in some records and not others is typed as optional, and a value that is sometimes null widens accordingly. Generators that read only the first element get this wrong on exactly the payloads where it matters.
- What happens to a key that is a reserved word?
- It is renamed to something legal in the target language, and where the language supports it, an annotation records the original JSON key so serialisation still round-trips.