logo
GeekFormat

JSON to Go

Paste JSON on the left, and the right side automatically generates struct type definitions ready for direct use in Go projects. Pure browser-local processing, no registration or upload required.

Related

About JSON to Go: Turning JSON into Go's strongly-typed structs

JSON to Go is the process of automatically converting JSON-formatted data into Go language struct type definitions. JSON is the most common data interchange format in REST APIs, config files, message queues and logs, while Go is a strongly-typed language. In development, it is often necessary to map JSON's dynamic structure to structs before deserializing with encoding/json. Writing structs manually, especially with nested objects, is prone to missing fields or wrong types; this tool aims to automate that repetitive labor.

Go's struct is a composite data type, declared with `type Name struct { ... }`. Each field consists of a name and type; field names must start with an uppercase letter to be accessible from other packages, known as 'exported identifiers'. The tool automatically converts JSON field names to PascalCase exported field names, e.g. `user_name` maps to `UserName`, while preserving the original key in the json tag.

The core conversion of this tool is done by the in-browser jsonFormat Web Worker, calling quicktype-core's Go renderer with `just-types` and `no-comments` options. The entire flow does not depend on backend services: input JSON is parsed locally, types inferred, Go code generated, and finally presented in the right-side editor.

Type inference follows conventional JSON-to-Go mapping: strings map to `string`, booleans to `bool`, integers to `int64`, floats to `float64`, arrays to slices `[]T`, objects to independent structs, `null` to `interface{}`. Nested objects are processed recursively, maintaining clear hierarchy.

Compared to manual writing, tool-generated code is a 'runnable first draft'. Developers typically only need to fine-tune the root type name, package name, field type precision (e.g. int64 to int) and whether to use pointer types before placing it into real Go projects. Combined with one-click copy and model.go download, it significantly reduces repetitive work during integration and modeling phases.

Use Cases

  • Go backend development converts REST API response JSON to structs, directly binding to Gin/Echo/Fiber handler parameters with json.Unmarshal
  • During frontend-backend integration, take example response JSON from Postman, quickly generate Go models to reduce manual field typing
  • When integrating third-party Webhook callbacks, convert payload JSON to Go structs for convenient field-level access and validation
  • Convert JSON config files from Viper/Consul/Nacos to Go types, replacing weakly-typed map[string]interface{} access
  • Microservice teams unify gRPC/HTTP interface request/response structures, convert example JSON to shared Go types
  • Test engineers convert JSON fixtures to Go structs, use with testify for assertion-driven testing
  • Operations staff parse JSON log lines collected by ELK/Fluentd, generate structs then use Go programs for structured analysis
  • After crawlers scrape JSON data, convert to Go structs for use with gorm/gen or ent to generate database models
  • Convert JSON telemetry data reported by IoT devices to Go structs, for deserialization and filtering in edge gateway programs
  • Convert JSON messages consumed from Kafka/NATS/RabbitMQ to Go types for event-driven consumer implementation
  • SDK developers convert server example response JSON to Go structs, write into client library types package for user reference
  • Convert example JSON from Swagger/OpenAPI docs to Go structs as interface documentation code examples
  • Students or instructors convert example JSON to structs in Go courses, demonstrating Go's type system and json tag usage
  • Data migration scripts convert JSON rows exported from MySQL/PostgreSQL to Go structs for field mapping and type validation
  • Convert CI/CD config JSON to Go structs for strongly-typed config reading in pipeline tools written in Go
  • Refactor legacy code that reads JSON dynamically via maps to strongly-typed access based on structs

How to Use

  1. Paste JSON content in the left editor, or drag and drop .json/.txt files, or click 'Example' to load built-in data.
  2. Wait about 400ms; the tool will auto-convert and display the generated Go struct code on the right.
  3. If JSON errors occur, click the 'Fix JSON' button to automatically correct common format errors and continue generation.
  4. Check the right-side output, click 'Copy' to paste into your Go project, or click 'Download' to save as model.go file.

Features

  • Browser-local Go struct generation: JSON parsing and Go code generation complete within the browser, raw data not uploaded to server
  • 400ms debounce auto-conversion: no manual click needed after pasting or editing, copyable Go code output on the right in real time
  • Intelligent type inference: string maps to string, boolean to bool, integer to int64, float to float64, array to slice, object to struct
  • Automatic nested object expansion: recursively generates independent struct types, maintaining clear JSON hierarchy
  • Auto-generated json tags: fields include `json:"original_field_name"` tags, ready for use with encoding/json
  • One-click JSON error fix: automatically handles trailing commas, single quotes, missing quotes and other common format errors, continues generation after fix
  • Supports paste/upload/example input: drag and drop .json/.txt files, or load built-in example data
  • One-click copy and download: copy entire Go code to clipboard, or download as model.go file directly into project
  • localStorage input history: automatically saves recent input, quick recovery after refresh or accidental page close
  • Responsive split-screen editor: adjustable left/right panel width, comfortable input/output viewing on desktop and mobile

Code Examples

Deserialize JSON with generated struct

go

After copying the tool-generated struct into your project, you can directly deserialize API responses with encoding/json.

package main

import (
    "encoding/json"
    "fmt"
)

// 以下代码由 GeekFormat JSON 转 Go 工具生成
type User struct {
    ID      int64    `json:"id"`
    Name    string   `json:"name"`
    Tags    []string `json:"tags"`
    Address Address  `json:"address"`
}

type Address struct {
    City string `json:"city"`
}

func main() {
    data := []byte(`{
        "id": 1,
        "name": "Alice",
        "tags": ["admin", "dev"],
        "address": {"city": "Beijing"}
    }`)

    var u User
    if err := json.Unmarshal(data, &u); err != nil {
        panic(err)
    }

    fmt.Println(u.Name, u.Address.City)
}

Handle JSON with potentially missing fields

go

If certain API fields may not exist, change corresponding fields to pointer types or use with omitempty tags.

package main

import "encoding/json"

// 手动将字段改为指针,缺失时值为 nil
type User struct {
    ID      *int64  `json:"id,omitempty"`
    Name    *string `json:"name,omitempty"`
    Email   *string `json:"email,omitempty"`
}

func main() {
    data := []byte(`{"id": 1, "name": "Bob"}`)
    var u User
    json.Unmarshal(data, &u)
    if u.Email == nil {
        println("Email 字段缺失")
    }
}

FAQ

How do I convert JSON to Go struct?

Paste JSON content into the left input box; the tool will auto-convert within 400ms and display the generated Go struct on the right. You can also drag and drop .json/.txt files, or click 'Example' to load built-in data. After conversion, copy or download the model.go file with one click.

Does the generated Go code include json tags?

Yes. The tool generates Go code based on quicktype-core, and by default every struct field includes a `json:"original_field_name"` tag, convenient for direct serialization and deserialization with encoding/json's Unmarshal/Marshal.

Will JSON arrays be converted to Go slices?

Yes. JSON arrays generate corresponding slice types based on element types, e.g. `["a","b"]` generates `[]string`, `[1,2,3]` generates `[]int64`, `[{...},{...}]` generates custom types like `[]UserItem`.

Will nested objects generate multiple structs?

Yes. Every nested object recursively generates an independent struct type, named in PascalCase. For example, the `address` object generates an `Address` struct, referenced in the main struct via the `Address Address` field.

What type is generated for null values?

Null values in JSON are usually inferred as `interface{}`, which is the safe fallback type. If you know the actual type of the field, you can add an example value in JSON, regenerate, then manually adjust to the specific type.

Can I customize the root struct name?

Yes. The tool uses the root type name (e.g. User) by default; after modifying the root type name in settings, all associated subtype names update synchronously, and the downloaded filename also changes accordingly.

What if JSON has format errors?

The tool automatically detects JSON validity. If there are common errors like trailing commas, single quotes, missing quotes, a 'Fix JSON' button appears. Clicking it will attempt automatic repair and regenerate the Go struct; when repair fails, the specific error location is indicated.

Will data be uploaded to the server? Is it private and secure?

No. All JSON parsing, type inference and Go code generation complete in your browser via Web Worker; input content and generated code are never uploaded to any server, nor recorded to the cloud. Sensitive JSON containing API keys, tokens or business data can be used safely.

Can the generated code be placed directly into a Go project?

Yes. The generated code is standard Go structs with json tags, can be directly copied into the project's types/ or models/ directory. We recommend fine-tuning type names and package names to match project naming conventions.

Is this tool free? Do I need to register?

Completely free, no registration or login required. Open the page and use immediately, with no feature restrictions, watermarks or forced login.

What size JSON files are supported?

The tool has no strict file size limit, but conversion speed and rendering performance depend on browser and device performance. We recommend processing JSON within 1MB for best experience; for very large JSON, process first with a JSON formatter or splitting tool.

Will numeric types uniformly generate float64?

No. The tool distinguishes integers and floats: integer fields generate int64, float fields generate float64. If you prefer more specific types like int, uint64, replace manually after generation.

Troubleshooting

Right side shows 'Please enter JSON data'

Left input box is empty or contains only whitespace. Please paste valid JSON, or click 'Example' to load data, or drag and drop .json/.txt files.

JSON parse failure indicated but error location not found

Click the 'Fix JSON' button below the input box; the tool will automatically attempt to fix trailing commas, single quotes, missing quotes, JS-style objects and other issues. After fixing, modified results will be highlighted.

Generated field names don't conform to Go naming conventions

The tool generates PascalCase field names from JSON keys. If keys contain Chinese or special characters, escaped field names may be generated. We recommend changing JSON keys to English lowercase or snake_case, then uniformly adjusting after generation.

null field generated as interface{}, want to change to specific type

Since null cannot infer a specific type, the tool uses interface{} as fallback. You can give the field an example value (e.g. "" or 0) in the source JSON, regenerate, then change the type to a concrete type like string/int64.

Large JSON causes page lag after conversion

Browser rendering of very large JSON and many structs consumes significant memory. Recommendations: ① Keep only example JSON with key fields; ② Split into multiple objects and convert separately; ③ Close other memory-intensive tabs.

Array element type inferred as []interface{}

When arrays are empty [] or element types are inconsistent, the tool uses interface{} as fallback. Add example elements of the same type, or manually change the type to a concrete slice type like []string, []int64 after generation.

Glossary

struct
Go's composite data type, used to combine multiple fields into one type. The main body of Go code generated by this tool is several struct definitions.
slice
Go's dynamic array type, syntax []T. This tool maps JSON arrays to corresponding slices, e.g. []string, []int64, []UserItem.
json tag
Backtick string after a Go struct field, like `json:"user_name"`, used to specify the field name for encoding/json serialization/deserialization. This tool auto-generates this tag.
interface{}
Go's empty interface type, can represent any value. This tool uses interface{} as a safe fallback when encountering JSON null or undetermined types.
PascalCase
Naming style with each word capitalized, e.g. UserName, AddressCity. Go requires exported fields to start with an uppercase letter, so this tool automatically converts JSON field names to PascalCase.
encoding/json
JSON encoding/decoding package in Go's standard library. Structs generated by this tool, with json tags, can directly use json.Unmarshal and json.Marshal.
unmarshal
The process of parsing JSON byte stream into Go values. After generating structs, the most common usage is calling json.Unmarshal(data, &user).
omitempty
Common option for Go json tags, like `json:"name,omitempty"`, indicating the field is omitted when zero-valued. This tool does not generate omitempty by default; add manually as needed after generation.

JSON Type to Go Type Mapping Quick Reference

This tool automatically infers corresponding Go types based on JSON value types; common mappings are as follows:

JSON Value ExampleGenerated Go TypeDescription
"hello"stringString direct mapping
true / falseboolBoolean value
42int64Number without decimal point
3.14float64Number with decimal point
nullinterface{}Safe fallback when specific type cannot be inferred
["a","b"][]stringString array
[1,2,3][]int64Integer array
[{...},{...}][]UserItemObject array, element type generated recursively
{"id":1}UserObject generates independent struct

Common Go Numeric Type Selection Recommendations

The tool defaults to int64 and float64; adjust as needed in actual projects:

ScenarioRecommended TypeReason
Regular integer IDs, countersint64Matches tool default, compatible with most JSON numbers
Database auto-increment primary keys known to be positiveuint64Avoids negative numbers, clearer semantics
32-bit systems or explicitly small-range integersint32Reduces memory usage
Prices, coordinates, scientific computingfloat64Matches tool default, standard floating-point precision
Precise currency calculationsdecimal.Decimal / intfloat64 has precision risks; recommend using shopspring/decimal or int in cents

Privacy & Security

All processing of this JSON to Go tool completes entirely locally in your browser: JSON parsing, type inference, Go code generation all execute on the client side via Web Worker. Input JSON content, uploaded files and generated Go code are never uploaded to any server, nor recorded, cached or stored in the cloud. After closing or refreshing the page, all input and output content is automatically cleared from memory; only localStorage retains your recent input history (clearable anytime). Suitable for processing JSON containing API keys, tokens, and sensitive business data.