JSON to Go Struct Generator
Convert any JSON object into Go struct definitions with correct json struct tags, proper Go type mappings, nested struct decomposition, pointer types for nullable fields, and omitempty tags — paste the output directly into your Go package and start unmarshaling immediately.
Convert any JSON object into Go struct definitions with correct json struct tags, proper Go type mappings, nested struct decomposition, pointer types for nullable fields, and omitempty tags — paste the output directly into your Go package and start unmarshaling immediately.
This tool is designed to provide a seamless experience for developers by handling complex operations directly in your browser with maximum speed and security.
Go is a statically typed, compiled language — unlike JavaScript or Python, you cannot receive a JSON response and dynamically access its fields without first defining the data structure your code expects. To unmarshal a JSON response into Go, you define a struct whose fields correspond to the JSON fields you want to read, and the encoding/json package maps the JSON to the struct during unmarshaling. The struct field names must be exported (start with an uppercase letter) and the json struct tag on each field tells the encoder/decoder which JSON field name to map to that Go field.
Go's json struct tag system is the core of JSON interoperability in Go. A struct field like Username string `json:"username"` tells the encoding/json package that the Go field Username corresponds to the JSON field "username". Without the json tag, the package uses the Go field name as-is, which means a JSON field named "user_name" (snake_case) would not be decoded into a Go field named UserName (PascalCase) without the explicit mapping. The tag can also include options: `json:"username,omitempty"` means omit the field from JSON output if the value is the zero value for its type, and `json:"-"` means always exclude this field from JSON encoding and decoding.
JSON to Go struct conversion is the process of taking a JSON sample — typically an API response body — and generating the Go struct definitions that match its structure, with the correct Go types for each field and the correct json struct tags for each field name mapping. For a JSON response with 20 fields across 3 nested objects, this means writing 3 struct definitions with 20 fields and 20 json tags. This is mechanical work that takes time and is error-prone — a single wrong tag name or wrong type causes silent incorrect behavior or a runtime panic when the field is accessed. This tool generates all of it automatically.
This tool takes a JSON object and generates the Go struct definitions needed to unmarshal it using encoding/json. It infers the correct Go type for each JSON field: JSON strings become string, integers become int64, floats become float64, booleans become bool, JSON arrays become []ElementType with the element type inferred, and JSON null values become pointer types (*string, *int64, etc.) since Go uses pointers to represent nullable values — a nil pointer represents JSON null. JSON nested objects become separate named Go struct types, generated and composed correctly. Each struct field is generated with the correct json struct tag mapping the PascalCase Go field name to the original JSON field name. A JSON field named user_id becomes UserId string `json:"user_id"` in the Go struct — preserving the exact JSON field name in the tag so encoding/json maps it correctly. Fields derived from JSON null values get pointer types and the omitempty option in their tag is available as an option since a zero-value pointer is nil and would be omitted in JSON output. The generated code follows Go naming conventions: field names are PascalCase (exported), struct names are PascalCase and descriptive, and the overall structure follows the Go standard library style. The generated code includes a package declaration and the import for encoding/json so you can paste the output directly into a new .go file or into an existing file in your package. All type inference and code generation runs locally in your browser — your JSON API response data, including any sensitive fields or internal data model structures, never leaves your machine. The output is ready to use with json.Unmarshal(data, &yourStruct) or with encoding/json.NewDecoder for HTTP response bodies.
1. Paste your JSON into the Input JSON field — use a real API response sample that shows the complete structure including all fields. A single representative JSON object works best. If the API returns an array, paste one element since the tool generates the struct for a single item — you use []YourStruct for the array. Click Load Example to see a sample multi-field nested JSON before using your own data.
2. Click Generate Go Structs — the tool parses every field in your JSON, infers the correct Go type, generates PascalCase field names with the appropriate json struct tags, creates separate named struct types for nested objects, uses pointer types for null JSON values, and outputs the complete Go code with package declaration and encoding/json import in the result panel.
3. Review the generated struct types — check that the inferred types match your API's actual type contract. JSON integers default to int64 which is correct for most cases, but if your API returns values that are always small and you want int, change them. Check that JSON null fields correctly use pointer types in the generated output. If a field appears as null in your sample but you know it is always a specific type in real responses, change the pointer type to the concrete type.
4. Rename the generated struct types to meaningful names for your domain — the tool generates names based on the JSON structure, but names like AutoGeneratedStruct or NestedObject0 should be renamed to User, Profile, Address, or whatever the data actually represents. Go struct names are part of your API — they appear in function signatures, error messages, and documentation — so choosing meaningful names matters.
5. Copy the generated code and paste it into your Go package — create a new file like models.go or api_types.go and paste the generated structs. Add the file to your package, import encoding/json where you need it, and unmarshal your API responses using json.Unmarshal(responseBody, &yourStruct) or json.NewDecoder(resp.Body).Decode(&yourStruct) for HTTP responses.
Every Go developer working with external REST APIs goes through the same workflow: get the API documentation, look at a sample response, and write the Go structs to unmarshal it. Writing those structs is the least interesting part of the work — you are just mechanically mapping JSON field names to Go field names, assigning the right types, and writing json tags. For a simple API response with 10 fields it takes 10 minutes. For a complex response with multiple nested objects and 40 fields it takes 40 minutes, and the chance of making a typo in a json tag that causes silent misdeserialization grows with every field. The specific Go gotcha that this tool prevents is the silent fail on json tag mistakes. If you write `json:"userId"` but the actual JSON field is "user_id", encoding/json will not report an error — it will silently skip the field and leave the Go struct field at its zero value. Your code compiles and runs, but the field is always empty or zero, and you spend an hour debugging why a field that is clearly in the API response is not being populated. The tool generates the exact tag string matching the JSON field name from your sample, eliminating this category of bug entirely. Go's encoding/json package also handles pointer types differently from value types during unmarshaling and marshaling, and knowing when to use a pointer field versus a value field is a subtle but important design decision. When a JSON field is sometimes null or sometimes absent, using a value type means the zero value (empty string, zero integer) is indistinguishable from an absent value. Using a pointer type (*string, *int64) means nil represents absent and non-nil represents present, which lets you distinguish between "the API returned null for this field" and "the API returned 0 for this field." This tool generates pointer types for JSON null fields automatically, applying the correct Go idiom without requiring you to manually identify which fields need pointer types.
Correct json struct tags — generates the exact json:"fieldName" tag for every field matching the original JSON key so encoding/json maps fields correctly without any silent mismatches
Pointer types for null fields — JSON null values generate pointer types (*string *int64 *bool etc.) which is the correct Go idiom for distinguishing between null and zero-value
Nested struct decomposition — generates separate named struct types for every nested JSON object and composes them correctly in the parent struct
PascalCase field names with correct tags — converts snake_case and camelCase JSON field names to PascalCase Go field names while preserving the original key in the json tag
Package declaration and imports included — output includes the package declaration and encoding/json import so you can paste directly into a new Go file
Correct Go type inference — JSON strings become string integers become int64 floats become float64 booleans become bool and arrays become the correct Go slice type
100% browser-based — your JSON API response data never leaves your machine making it safe to use with internal API responses or sensitive data structures
Instant generation — all type inference and code generation runs locally in your browser with no server round-trip
Generating Go structs for third-party REST API responses to use with encoding/json and json.Unmarshal
Creating Go types for HTTP client responses in services built with net/http or popular Go HTTP clients like resty or go-resty
Generating struct definitions for JSON data received from message queues like NATS Kafka or RabbitMQ
Creating Go types for JSON configuration files read with encoding/json or viper
Generating structs for JSON data stored in Redis or other key-value stores accessed from Go services
Bootstrapping Go model types when implementing a REST API client package for a third-party service
Creating Go struct definitions for JSON payloads received through WebSocket connections
Generating Go types for JSON-formatted log entries parsed by a log processing service
Example Input
{
"id": 1,
"username": "priya_singh",
"email": "priya@learnhubly.com",
"is_active": true,
"score": 98.5,
"profile": {
"bio": "Principal Software Engineer",
"skills": ["Go", "React", "TypeScript"]
},
"deleted_at": null
}Example Output
package main
import "encoding/json"
type Profile struct {
Bio string `json:"bio"`
Skills []string `json:"skills"`
}
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
IsActive bool `json:"is_active"`
Score float64 `json:"score"`
Profile Profile `json:"profile"`
DeletedAt *string `json:"deleted_at"`
}
// Usage:
// var user User
// err := json.Unmarshal(data, &user)
// or
// err := json.NewDecoder(resp.Body).Decode(&user)Invalid JSON: The tool requires valid JSON before it can generate Go structs. If your JSON has syntax errors — missing commas, unquoted keys, trailing commas, single quotes — the generation will fail. Use the JSON Formatter and Validator tool to fix syntax errors first, then paste the corrected JSON here.
Empty Input: The tool requires at least one JSON field to generate a struct. If you click Generate Go Structs with an empty input field, the tool will prompt you to enter JSON. Paste a JSON object starting with { or a JSON array starting with [ before generating.
Generated Struct Names Are Generic: The tool generates struct names based on the JSON structure — the top-level object becomes AutoGeneratedStruct or a similar generic name, and nested objects get names like NestedObject. These names must be renamed to meaningful names that match your domain before using the code in production. Go struct names appear in function signatures and error messages and are part of your package's public API — always rename generated structs to descriptive names like User, Product, or APIResponse.
Pointer Type Confusion for Null Fields: Fields that appear as null in your JSON sample are generated with pointer types (*string, *int64, etc.). If you forget that these fields are pointers and try to use them directly where a non-pointer type is expected, the Go compiler will report a type mismatch. To use the value from a pointer field, dereference it: *user.DeletedAt, or check for nil first: if user.DeletedAt != nil { use(*user.DeletedAt) }. The encoding/json package sets pointer fields to nil for JSON null values and leaves them nil for absent fields.
Type Inference Limitations for Union Types: JSON fields that contain different types in different responses — a field that is sometimes a string and sometimes an integer, or sometimes an object and sometimes null — cannot be correctly represented by a single Go type. The tool infers the type from your sample, so it will pick one type based on what appears in the JSON you pasted. For fields with genuinely mixed types, use interface{} (or any in Go 1.18+) as the field type and handle the type assertion at runtime, or restructure the JSON model to avoid union types.
Not checking json tag field names against the actual API response
Fix: The tool generates json tags based on the JSON sample you paste. If the JSON sample has a field spelled differently from the actual API response — for example the documentation shows 'user_id' but the API actually returns 'userId' — the generated tag will be wrong and encoding/json will silently skip the field, leaving it at its zero value. Always verify the generated tags against a real API response from the actual endpoint, not just from documentation. Log the raw response body before unmarshaling and compare field names to the generated struct tags. A single character difference in case causes a silent unmarshal miss that compiles and runs without errors.
Using the generated struct directly without adding validation for required fields
Fix: The generated struct has no validation — encoding/json will happily unmarshal a JSON response where required fields are absent, leaving those fields at their zero values without any error. A string field that should always be present will be an empty string if absent from the response. An int64 that should always be a positive ID will be 0. To add validation, either check field values after unmarshaling (if user.ID == 0 { return ErrInvalidResponse }), or use a validation library like go-playground/validator with struct tags, or implement the json.Unmarshaler interface on the struct to add custom validation logic.
Ignoring the difference between json.Unmarshal and json.NewDecoder
Fix: Both decode JSON into Go structs, but they are designed for different use cases. json.Unmarshal takes a []byte of the complete JSON payload — use this when you already have the full response body as bytes, for example after ioutil.ReadAll(resp.Body). json.NewDecoder takes an io.Reader and streams the JSON — use this when you are decoding directly from an HTTP response body with json.NewDecoder(resp.Body).Decode(&struct), which is more memory-efficient for large responses because it does not read the entire body into memory first. For most REST API responses, the decoder approach is preferred: defer resp.Body.Close() and json.NewDecoder(resp.Body).Decode(&result).
Not understanding that encoding/json ignores unknown JSON fields by default
Fix: By default, encoding/json silently ignores any JSON fields that do not have a corresponding struct field. If the API adds a new field to its response and your Go struct does not have a matching field, the new field is silently discarded during unmarshaling — your code continues to work but does not have access to the new field. This is generally the correct behavior for robust API clients that should not break when the API adds fields. If you want to detect unexpected fields and fail, use a decoder with DisallowUnknownFields: dec := json.NewDecoder(body); dec.DisallowUnknownFields(). Use this in tests to catch API response changes early, not in production where it could break your service when the API evolves.
Using the generated struct fields without handling the zero value correctly
Fix: Go's zero value for each type is the default when a JSON field is absent or when unmarshaling fails: string fields default to empty string, int fields to 0, bool to false, slice to nil, pointer to nil. This creates ambiguity: an int64 field with value 0 could mean the API returned 0 or that the field was absent. For fields where the zero value is a valid API value (a count of 0, an empty string username), use pointer types in the struct so nil represents absent and non-nil represents present. For fields where zero is not a valid value (a non-zero ID), checking for zero is sufficient to detect absent fields.
JSON Cheatsheet
Interactive reference guide for valid JSON syntax, data types, parsing/stringifying methods, schema validation rules, and language integrations.
Regex Cheatsheet
Interactive guide to Regex anchors, character classes, quantifiers, lookarounds, capturing groups, and search flags.
HTTP Headers Cheatsheet
Complete guide to standard and security HTTP headers including Authorization, CORS control, caching policies, and CSP directives.
SQL Cheatsheet
Complete guide to SQL statements including SELECT queries, WHERE filters, aggregate functions, JOIN types, and DDL commands.
Does it support nested objects?
Yes. Nested JSON objects are generated as separate named Go struct types and composed correctly in the parent struct. A JSON field whose value is an object becomes a field of a named struct type — for example a profile object in the JSON becomes a Profile struct in Go with its own fields and json tags. Deeply nested structures are handled recursively, with each level of nesting generating its own struct type. After generating, rename the struct types from the generic generated names to meaningful domain names like User, Profile, Address, or whatever the data represents.
Are JSON tags included?
Yes. Every struct field is generated with the correct json struct tag mapping the PascalCase Go field name to the original JSON field name. A JSON field named user_id generates UserId int64 `json:"user_id"` in Go. A field named createdAt generates CreatedAt string `json:"createdAt"`. The json tag is what tells encoding/json how to map between the JSON field names and the Go struct field names — without it, the package uses the Go field name verbatim which would not match snake_case or camelCase JSON field names.
How do I unmarshal JSON into the generated struct?
Two approaches depending on your input. For JSON as a byte slice: var result YourStruct; err := json.Unmarshal(data, &result). For an HTTP response body: var result YourStruct; err := json.NewDecoder(resp.Body).Decode(&result); don't forget defer resp.Body.Close(). For a JSON string: err := json.Unmarshal([]byte(jsonString), &result). If the JSON is an array at the top level, unmarshal into a slice: var results []YourStruct; err := json.Unmarshal(data, &results). Always check the returned error — a non-nil error means the JSON did not match the struct structure.
What Go types are inferred for different JSON values?
JSON strings become string. JSON integers become int64 (not int, because int64 handles the full range of JSON integer values). JSON floats become float64. JSON booleans become bool. JSON arrays become []ElementType with the element type inferred from the array contents. JSON null values become pointer types — *string, *int64, *bool, or *StructName — since a nil pointer represents the absence of a value, which is the Go idiom for nullable fields. JSON nested objects become named struct types. If a JSON field contains different types in different elements, the tool uses interface{} as a fallback type.
What is the omitempty struct tag option and when should I use it?
The omitempty option in a json tag — like `json:"fieldName,omitempty"` — tells encoding/json to omit the field from the JSON output when marshaling if the field has its zero value (empty string, zero integer, false boolean, nil pointer, empty slice). It has no effect during unmarshaling — it only affects json.Marshal output. Use omitempty on fields that should not appear in the marshaled JSON when they are absent or unset — for example optional fields in a request body or fields that have meaningful default behavior when absent. Do not use omitempty on fields that should always be present in the output even when they are zero or empty.
How do I handle JSON arrays at the top level?
If the API returns a top-level JSON array, the generated struct describes one element. Unmarshal into a slice of that struct: var items []YourStruct; err := json.Unmarshal(data, &items). For paginated responses with a wrapper like {data: [...], total: 100}, generate the struct from the full wrapper object — the tool will create a struct with a Data field of type []ItemStruct and a Total field of type int64.
Can I use the generated struct with popular Go HTTP client libraries?
Yes. The generated structs work with any Go HTTP client that uses encoding/json for response decoding. With the standard library net/http, use json.NewDecoder(resp.Body).Decode(&result). With the resty library, use client.R().SetResult(&result).Get(url) and resty handles the JSON decoding automatically. With go-resty, the approach is similar. With the fasthttp library, use json.Unmarshal(ctx.Response.Body(), &result). The generated structs are plain Go structs with standard encoding/json tags — they work with any library that respects the encoding/json interface.
What is the difference between using a struct and using map[string]interface{} for JSON in Go?
map[string]interface{} lets you decode any JSON without defining a struct — encoding/json maps JSON fields to map keys with interface{} values representing the JSON values. This is flexible but forces you to type-assert every value you access: userMap["name"].(string), userMap["age"].(float64). Type assertion failures cause panics at runtime. Struct-based decoding gives you compile-time type safety — accessing user.Name is always a string without any assertion. For any JSON structure you will access frequently, a struct is faster to access, safer, and produces better code. Use map[string]interface{} only when the JSON structure is genuinely unknown at compile time, such as when forwarding arbitrary JSON between services.
Data Conversion Best Practices for Developers – Complete Guide 2026
Data Conversion Best Practices for Developers in 2026. In-depth guide covering JSON, XML, CSV, Markdown conversions, data integrity, security risks, performance optimization, and expert strategies from a Principal Software Engineer with 15+ years experience.
What is JSON? How to Format, Validate & Use It (Complete Guide 2026)
What is JSON? How to Format, Validate & Use It (Complete Guide 2026). In-depth explanation of JSON syntax, real-world use cases, formatting best practices, common mistakes, advantages, disadvantages, and expert tips from a Principal Software Engineer with 15+ years experience.
How to validate JSON online (step-by-step guide)
Invalid JSON can break your application. Follow this guide to quickly validate and fix your JSON data.
Recent Activity
No recent activity