JSON to Go Struct

Generate Go structs from JSON

Try an example
Root struct name:

JSON Input

Go Output

Runs locally Β· Safe to paste secrets
Go structs will appear here…

What is JSON to Go Conversion?

JSON to Go conversion turns raw JSON data into Go type definitions that work with the encoding/json package in Go's standard library. Go is statically typed, so every JSON field needs a corresponding struct field with the correct type and a struct tag that tells the serializer which JSON key to map. Writing these definitions by hand for large or deeply nested API responses is slow and easy to get wrong.

The encoding/json package, defined in the Go specification since Go 1.0, uses reflection to match JSON keys to exported struct fields. The matching is case-insensitive by default, but explicit json struct tags are the standard practice because they remove ambiguity and let you use Go's PascalCase convention while the JSON stays in camelCase or snake_case. A converter automates this: it reads your JSON, infers Go types from the values, and outputs struct definitions with the correct tags.

Go's type system maps cleanly to JSON. Strings become string, booleans become bool, integers become int, and floating-point numbers become float64. Nested JSON objects become separate named structs, and arrays become slices. The one gap is null: Go has no universal nullable type, so null values typically become pointer types (*string, *int) or interface{}. A generator handles all of this in milliseconds.

Why Use a JSON to Go Converter?

Defining Go structs from JSON by hand means counting braces, guessing types, and rewriting tags every time the API changes. A converter removes that friction.

⚑
Instant type generation
Paste your JSON and get correct Go struct definitions in under a second. No manual field typing, no missed tags, no alignment headaches.
πŸ”’
Privacy-first processing
Conversion runs entirely in your browser. Your JSON never leaves your machine. API keys, tokens, and user data stay private.
🏷️
Correct struct tags
Every generated field includes a json struct tag that maps the Go field name to the original JSON key. This prevents silent mismatches during json.Unmarshal.
πŸ“¦
No install or signup
Open the page and paste your JSON. No Go toolchain required, no CLI tools to install, no account to create.

JSON to Go Use Cases

REST API Client Development
Generate request and response structs for third-party REST APIs. Paste sample JSON from API docs and get types ready for http.Client and json.NewDecoder.
gRPC Gateway Models
When a Go service exposes both gRPC and REST endpoints, you need Go structs that match the JSON payloads. Convert the JSON shape into structs that match your protobuf definitions.
DevOps Configuration Parsing
Parse JSON config files (Terraform outputs, Kubernetes manifests, CI/CD pipeline configs) into typed Go structs for custom tooling and automation scripts.
Data Pipeline Processing
Build Go structs for JSON records from message queues (Kafka, RabbitMQ, SQS) or data lakes. Typed structs catch schema changes at compile time instead of runtime.
Test Fixture Setup
Convert JSON test fixtures into Go structs for table-driven tests. Type-safe fixtures make test failures easier to diagnose than raw map[string]interface{} assertions.
Learning Go's Type System
Students and developers coming from dynamic languages can paste familiar JSON and see how Go represents the same data with explicit types, pointers, and struct tags.

JSON to Go Type Mapping

The encoding/json package follows specific rules when mapping JSON values to Go types. The table below shows the default mapping and common alternatives. The "Default" column is what most generators produce. The "Alternative" column shows types you might choose based on your requirements, such as int64 for large IDs or pointer types for nullable fields.

JSON TypeExampleDefaultAlternative
string"hello"stringstring
number (integer)42intint64
number (float)3.14float64float64
booleantrueboolbool
nullnullinterface{}*string / *int
object{"k": "v"}structstruct
array of strings["a", "b"][]string[]string
array of objects[{"id": 1}][]Item[]Item
mixed array[1, "a"][]interface{}[]interface{}

Go JSON Struct Tag Reference

Struct tags control how encoding/json serializes and deserializes fields. The json tag is by far the most common, but you can combine it with other tags (db, yaml, xml) on the same field. The tag syntax is a backtick-delimited string after the field type. Here are the json tag options that encoding/json supports.

TagBehaviorUse Case
json:"name"Maps struct field to JSON key "name"Always generated
json:"name,omitempty"Omits field from output if zero valueOptional fields
json:"-"Field is never serialized or deserializedInternal fields
json:"name,string"Encodes int/bool as JSON stringString-encoded numbers

json.Unmarshal vs json.NewDecoder

Go provides two ways to decode JSON: json.Unmarshal for byte slices and json.NewDecoder for io.Reader streams. Both use the same struct tag rules, but they differ in when to use them.

json.Unmarshal
Takes a []byte and populates a struct. Best for JSON that is already fully in memory: HTTP response bodies read with io.ReadAll, file contents, or test fixtures. Returns an error if the JSON is malformed or types do not match.
json.NewDecoder
Wraps an io.Reader and decodes JSON tokens as they arrive. Best for streaming sources: HTTP response bodies read directly, newline-delimited JSON (NDJSON) logs, or large files you do not want to load entirely into memory. Call Decode() in a loop with More() for multi-object streams.

Code Examples

These examples show how to use Go structs generated from JSON in real programs, plus how to generate them from other languages. The Go examples use encoding/json from the standard library.

Go (json.Unmarshal)
package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	ID       int      `json:"id"`
	Name     string   `json:"name"`
	Email    string   `json:"email"`
	IsActive bool     `json:"is_active"`
	Tags     []string `json:"tags"`
}

func main() {
	data := []byte(`{"id":1,"name":"Alice","email":"alice@example.com","is_active":true,"tags":["admin","editor"]}`)

	var user User
	if err := json.Unmarshal(data, &user); err != nil {
		panic(err)
	}
	fmt.Println(user.Name)  // β†’ Alice
	fmt.Println(user.Tags)  // β†’ [admin editor]
}
JavaScript (fetch + type reference)
// JSON response from API β€” this is the shape you'd convert to Go:
const res = await fetch("https://api.example.com/users/1");
const user = await res.json();
// user β†’ { "id": 1, "name": "Alice", "email": "alice@example.com" }

// Equivalent Go struct:
// type User struct {
//     ID    int    `json:"id"`
//     Name  string `json:"name"`
//     Email string `json:"email"`
// }
Python (generate Go structs from JSON)
import json

def json_to_go(data: dict, name: str = "Root") -> str:
    lines = [f"type {name} struct {{"]
    type_map = {str: "string", int: "int", float: "float64", bool: "bool"}

    for key, value in data.items():
        go_type = type_map.get(type(value), "interface{}")
        field = key.title().replace("_", "")  # snake_case β†’ PascalCase
        lines.append(f'\t{field} {go_type} `json:"{key}"`')
    lines.append("}")
    return "\n".join(lines)

data = json.loads('{"user_name": "Alice", "age": 30, "verified": true}')
print(json_to_go(data))
# type Root struct {
#     UserName string `json:"user_name"`
#     Age      int    `json:"age"`
#     Verified bool   `json:"verified"`
# }
Go (json.Decoder for streams)
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

type Event struct {
	Type    string `json:"type"`
	Payload string `json:"payload"`
}

func main() {
	stream := strings.NewReader(`{"type":"click","payload":"btn-1"}
{"type":"scroll","payload":"page-2"}`)

	dec := json.NewDecoder(stream)
	for dec.More() {
		var ev Event
		if err := dec.Decode(&ev); err != nil {
			break
		}
		fmt.Printf("%s: %s\n", ev.Type, ev.Payload)
	}
	// β†’ click: btn-1
	// β†’ scroll: page-2
}

Frequently Asked Questions

What is the difference between json.Unmarshal and json.Decode?
json.Unmarshal takes a []byte containing the full JSON document and populates a struct. json.NewDecoder wraps an io.Reader and decodes JSON incrementally. Use Unmarshal when you already have the complete JSON in memory (e.g., after io.ReadAll). Use NewDecoder when reading directly from an HTTP response body, a file, or any streaming source where you want to avoid buffering the entire payload.
How does Go handle JSON fields that are missing from the payload?
Missing JSON fields leave the corresponding Go struct field at its zero value: "" for strings, 0 for numbers, false for bools, nil for pointers and slices. If you need to distinguish between "field missing" and "field present but zero," use a pointer type like *int or *string. A nil pointer means the field was absent; a non-nil pointer with a zero value means it was explicitly set to 0 or "".
Why do Go struct fields need to be exported (capitalized) for JSON?
The encoding/json package uses reflection to access struct fields, and Go's reflection rules only allow access to exported (uppercase) fields. If a field starts with a lowercase letter, encoding/json cannot see it and will silently skip it during both marshaling and unmarshaling. Use the json struct tag to map an exported PascalCase field to a lowercase JSON key.
How do I handle snake_case JSON keys in Go?
Add a json struct tag with the exact JSON key name. For example, a JSON field "user_name" maps to a Go field UserName with the tag `json:"user_name"`. The generator handles this automatically. There is no global option in encoding/json to set a naming policy; each field must declare its own tag.
Can I convert JSON with null values to Go?
Yes. Null JSON values map to pointer types in Go. A field like "age": null becomes Age *int `json:"age"`. When the JSON value is null, the Go pointer is nil. When it has a value, Go allocates an int and the pointer references it. For fields that are always nullable, using a pointer is the idiomatic approach in Go.
What happens if JSON contains a number larger than Go's int can hold?
Go's int is platform-dependent (32-bit on 32-bit systems, 64-bit on 64-bit systems). For large numbers like JavaScript timestamps or database IDs, use int64 explicitly. If the JSON number has decimal places, use float64. For numbers that exceed float64 precision (e.g., large financial values), use json.Number, which keeps the raw string representation and lets you parse it yourself.
How is this browser tool different from the json-to-go command-line tool?
This browser tool converts JSON to Go struct definitions instantly without installing anything. The json-to-go CLI (available via go install) does the same thing from the command line, which is useful for automation, scripts, or CI pipelines. Both produce valid Go structs with encoding/json struct tags. Choose the browser tool for quick ad-hoc conversions and the CLI for programmatic or pipeline use.