Go Struct Generator
Generate Go structs from representative JSON or one PostgreSQL or MySQL table definition, with explicit field mappings and review notes.{{ summaryTitle }}
{{ summaryLine }}
{{ computation.values.go_struct_source }}
The chart renderer is unavailable. Type counts remain available in the field mapping.
| Source | Go field | Go type | Tags | Copy |
|---|---|---|---|---|
| {{ row.source_path }} | {{ row.go_field }} | {{ row.go_type }} | {{ row.tags || '—' }} |
- {{ note }}
No ambiguous mappings were found in this sample. Compare the generated fields with the authoritative API or database schema before use.
A Go struct describes a record as named fields with declared types. It can model an API payload, configuration document, database row, or another data shape, but the declaration is only useful when its field types match the real contract. Sample-driven generation shortens the first draft; it cannot prove what future records are allowed to contain.
JSON and SQL provide different kinds of evidence. JSON contains values, so a generator infers types from examples: a whole number suggests an integer, a quoted value suggests a string, and an object suggests another struct. A CREATE TABLE statement declares column types and nullability more directly, but its database types still need deliberate Go equivalents.
| Source | Strong evidence | Missing evidence | Main review risk |
|---|---|---|---|
| Representative JSON | Observed keys, nested shapes, values, nulls, and array members | Unseen optional fields, full numeric ranges, and future variants | A narrow sample can produce a type that is too strict. |
| SQL table definition | Declared column types, order, and basic nullability | Application validation, joins, generated behavior, and custom scanning rules | A database type may not have a lossless standard Go equivalent. |
Nullability is a modeling decision, not a cosmetic style. A pointer can distinguish an absent or SQL NULL value from a type's zero value. A value field is simpler to use, but it merges those states. The right choice depends on the API or database contract and on how decoding or row scanning is handled in the project.
Struct tags preserve source field names after they are converted to exported Go identifiers. A key such as display_name can become DisplayName while a JSON or database tag keeps the original spelling. Tags do not validate data, rename database columns, or select an object-relational mapper; downstream code decides how to interpret them.
Numbers deserve extra caution. JSON has a single number grammar, while Go distinguishes integer and floating-point types. SQL decimal types may represent exact financial quantities that should not be stored in float64. Generated numeric fields are scaffolding until the authoritative schema, expected range, precision, and null behavior have been checked.
Generated source should compile cleanly, but compilation alone is not contract verification. Compare every field with API documentation, schema migrations, representative edge cases, and project-specific types before adding the declaration to production code.
How to Use This Tool:
Choose the grammar that owns the source, then review the generated mapping as a draft of the real data contract.
- Select Representative JSON or SQL CREATE TABLE. JSON accepts one object or an array of objects; SQL accepts one PostgreSQL or MySQL table statement.
- Paste the source, then enter a valid lower-case Package name and an exported Root type name. In SQL mode, select the database dialect instead of relying on type-name guessing.
- Choose the struct tags needed by downstream code. Use JSON tags, database tags, both, or no tags.
- Set the nullable and JSON number policies. Enable timestamp inference only when the source contract confirms that matching strings are timestamps; sort fields only when alphabetical order is preferred over source order.
- Inspect Field mapping and Review notes before copying the Go source. Resolve mixed types, missing fields, unsupported SQL types, decimal precision, and zero-value warnings against the authoritative contract.
Interpreting Results:
Go struct source is a compilable scaffold containing the package clause, any required standard-library imports, and generated struct declarations. Field mapping is the audit trail: it connects each source path or column to its exported field, Go type, and tags. Review that table before focusing on the type-count chart.
Review notes identify evidence that cannot safely resolve itself, including missing or null JSON values, mixed sample types, empty arrays, renamed fields, unsupported SQL types, decimal-to-floating-point mappings, and nullable fields emitted as values. A result with no notes still reflects only the supplied sample or table statement.
The type profile shows how many fields use each generated type. It can reveal an unexpected concentration of any or pointers, but it does not rank correctness. Verify types against the contract, run the project's formatter and compiler, and test decoding or database scanning with edge cases.
Technical Details:
Generation is a bounded source-to-type transformation. JSON values are merged into a structural shape before names and Go types are allocated. SQL columns are parsed from one table definition and mapped according to the chosen database dialect. Both paths finish by applying nullability, tags, field order, imports, and Go identifier rules.
Transformation Core
| Stage | JSON path | SQL path |
|---|---|---|
| Parse | Read one object or a non-empty array of objects. | Read one CREATE TABLE column list and the selected dialect. |
| Collect evidence | Walk nested values and merge up to 100 array samples. | Read column names, declared types, NOT NULL, and primary-key markers. |
| Resolve shape | Merge compatible types; mark missing or null fields as nullable. | Map database types to Go types and mark other columns nullable. |
| Name | Convert source names to exported identifiers, preserve common initialisms, and resolve collisions with numeric suffixes. | |
| Emit | Apply pointer or value policy, add selected tags and imports, then write package and struct declarations. | |
Rule Core
JSON inference uses observed values. When several samples reach the same path, their shapes are merged under these rules.
| JSON evidence | Generated base type | Merge or review behavior |
|---|---|---|
| String | string | A parseable timestamp-like string becomes time.Time only when timestamp inference is enabled. |
| Boolean | bool | Mixed with another kind, it becomes any. |
| Whole number | int64 or float64 | The JSON number policy decides the starting type; integer plus decimal evidence becomes float64. |
| Decimal number | float64 | Range and precision still require contract review. |
| Object | Nested struct | Fields are merged across object samples; an absent field becomes nullable. |
| Array | Slice of the merged item type | An empty array becomes []any; at most the first 100 items are sampled. |
null | Nullable matching type, or any without other evidence | Pointer mode adds a pointer only when the resolved type is pointer-eligible. |
| Incompatible kinds | any | A review note records the mixed evidence. |
SQL mapping follows declared type families. PostgreSQL arrays add a slice around the mapped element type. Table-level constraints are skipped, while inline NOT NULL and primary-key markers make a column required.
| Go type | PostgreSQL examples | MySQL examples | Review note |
|---|---|---|---|
int | smallint, integer, serial | tinyint, smallint, mediumint, int | MySQL tinyint(1) maps to bool. |
int64 | bigint, bigserial | bigint, year | Confirm unsigned ranges and project conventions. |
float64 | real, double precision, numeric, money | float, double, decimal, fixed | Exact decimal-like types generate a precision warning. |
string | Text, character, UUID, network, XML, interval, and name types | Character, text, enum, and set types | Database-specific validation is not reproduced. |
time.Time | Date, time, timestamp, and time-zone variants | date, datetime, timestamp, time | The time import is added. |
json.RawMessage | json, jsonb | json | The encoding/json import is added. |
[]byte | bytea | Binary, blob, and bit families | Encoding and scanning behavior remain project concerns. |
any | Any unsupported declared type | Replace it with the project's real type before use. | |
Names are split at punctuation and case changes, converted to exported Go form, and normalized for common initialisms such as ID, URL, HTTP, JSON, SQL, and UUID. Leading digits are removed. A keyword-like name receives a Value suffix, and generated collisions receive numeric suffixes. Tags keep the original source spelling.
| Boundary | Maximum | Effect |
|---|---|---|
| Source | 100,000 characters | Larger input is rejected. |
| JSON depth | 20 levels | Deeper samples are rejected. |
| Sampled JSON values | 5,000 nodes | More complex samples are rejected. |
| Fields or SQL columns | 1,000 | Larger models are rejected. |
| Generated structs | 80 | Additional nested types are not emitted. |
| Array evidence | First 100 items per sampled array | Later variants do not influence inference. |
| Generated source | 200,000 characters | Oversized output is rejected. |
| Visible review notes | 30 distinct notes | Any additional note count is summarized. |
Source text is parsed locally as inert data or data-definition language. It is never executed, and SQL defaults, indexes, foreign keys, checks, generated expressions, methods, migrations, and object-relational behavior are not turned into Go code.
Accuracy Notes:
The output reflects supplied evidence, not the full runtime domain. Before use, confirm:
- optional and nullable fields against the API schema or database migration;
- integer ranges, exact decimals, identifiers, enums, timestamps, and custom scalar types;
- whether pointers, value types, or dedicated nullable wrappers match decoding and database-scanning conventions;
- that every generated tag is used by the intended serializer or database library;
- that root arrays and large nested arrays included enough varied records to expose optional and mixed fields.
Worked Examples:
Mixed JSON order samples
An array contains two order objects. The first has an integer quantity and no note; the second has a decimal quantity and a null note. Quantity becomes float64, note is nullable, and the review notes record both the mixed numeric evidence and the missing or null field. Those cues should be checked against the API schema before the generated types are accepted.
PostgreSQL invoice table
A table declares id bigint PRIMARY KEY, total numeric(12,2) NOT NULL, and nullable metadata jsonb. The draft uses int64 for ID, float64 for total with an exact-decimal warning, and a pointer to json.RawMessage for metadata under the pointer policy. A money-safe decimal type may be the necessary correction.
References:
- Struct types, The Go Programming Language Specification.
- Package encoding/json, Go standard library.
- The JavaScript Object Notation Data Interchange Format, RFC 8259, December 2017.
- Data types, PostgreSQL 18 documentation.
- Data types, MySQL 8.4 Reference Manual.