go-supertools
Developer & Data Tools

JSON to Go Struct Converter

Generate Go structs with json tags from sample JSON.

Runs in your browser Your input never leaves your device.

0 characters | 0 words

Report a problem with this tool

About this tool

Paste a sample of the JSON your service sends and get Go struct definitions you can use with encoding/json, with json tags that keep the original key names. Field names are exported and follow Go conventions, including initialisms such as ID, URL and API (user_id becomes UserID); optional and nullable values become pointers so that missing and zero are different, and optional fields get omitempty, which you can switch off. The shape is inferred from your sample: objects become named types, lists become list types, a key that is missing from some items of a list becomes optional, numbers without a fraction become integers (a list that mixes 1 and 2.5 is decimal), and a value that is sometimes one type and sometimes another becomes a union or a general type. The same shape in two places shares one type. Keys that are not valid names, such as 'user name', are converted and the original key is kept. To test the output we compiled it with the Go compiler for 37 samples, including awkward key names and reserved words, unmarshalled each sample, marshalled it again and compared the result with the original: the data matched every time. Two limits to know: a value that is null in a field that is also sometimes missing cannot be told apart after a round trip, and numbers that are whole in your sample become int64, so use a sample that shows the decimals if a field can have them. Your JSON is processed in your browser and never uploaded. A JSON number such as 10.0 or 1e3 is read as a whole number, because the sample loses how it was written; tick Treat all numbers as decimals if your values can have a fraction.

How to use it

  1. Paste a sample of your JSON, a longer or more varied sample gives a better result.
  2. Set the name of the top-level type, and the options.
  3. Copy the code into your project.
  4. Adjust names and types that the sample could not tell, such as dates in strings.

Common problems

A field is int64 but the API sometimes sends decimals
The sample only showed whole numbers. Add an example with a decimal to the sample, or change the type to float64.
A date is just a string
JSON has no date type. Change the field to time.Time if the format is RFC 3339, or keep string.
The struct is any for a field
The values had different types, or only null, so no single Go type fits. Use a sample with the real values, or define the type yourself.