Go's standard library provides excellent JSON support through the encoding/json package. Unmarshaling JSON into Go requires a struct where each field has a json struct tag corresponding to the JSON key. Writing these structs by hand for complex API responses is tedious and error-prone. Generating them from a JSON sample eliminates this work.
How Go JSON Unmarshaling Works
The json.Unmarshal function reads a JSON byte slice and populates a Go value. When the target is a struct, it matches JSON object keys to struct fields using the json struct tag. A field tagged with json:"name" is populated from the JSON key "name". The json tag value "-" skips the field. The omitempty option in a tag omits the field when marshaling back to JSON if the field has its zero value.
Field names in Go structs follow Go's PascalCase convention. The json tag preserves the original JSON key names (which are typically camelCase or snake_case).
The Generated Struct Format
A JSON object like {"userId": 1, "userName": "alice", "email": "alice@example.com"} generates a Go struct with three fields: UserId int (with json:"userId"), UserName string (with json:"userName"), and Email string (with json:"email"). The generator uses PascalCase for field names regardless of the JSON key casing.
Nested JSON objects become nested structs. JSON arrays become Go slices. Null values generate pointer types (like *string or *int) to allow null representation.
Refinements After Generation
Review the generated struct for accuracy. The generator infers types from the sample values. An ID field that appears as a number in the sample might actually be returned as a string in some API responses. Check the API documentation to confirm.
Fields that can be null should be pointer types. The generator may create these automatically, but verify that nullable fields are correctly handled.
Using the DevHexLab JSON to Go Tool
Open the tool at /tools/javascript/json-to-go. Paste a JSON sample. Copy the generated Go struct. Paste it into your Go file and import encoding/json. Use json.Unmarshal to decode the JSON into the struct.
Frequently Asked Questions
What if the JSON has inconsistent types for the same field?
If a JSON field is sometimes a string and sometimes null, the generated type should be *string (a pointer that can be nil). Review the generated output for fields that might need pointer types.
Can I use the struct for both reading and writing JSON?
Yes. The same struct with json tags works for both json.Unmarshal (reading) and json.Marshal (writing). Use the omitempty tag option to suppress zero-value fields when writing.
Generate the struct, import the package, unmarshal immediately.