All Recipes
StarVerified Developer Solution • 100% Offline
JSON to Go Struct

Fix "cannot unmarshal string into Go struct field of type int"

Solve Go json.Unmarshal errors when JSON types do not match your struct definitions.

The Problem (Error Root Cause)Exception

Your Go application panics with `json: cannot unmarshal string into Go struct field...`. The API returned a string (e.g., `"123"`) but your Go struct defined the field as an `int`.

Identified via runtime validation & stack traces
The Solution (Step-by-Step Fix)Verified

You can fix this by changing the struct field to `string` and parsing it manually, or by adding the `,string` tag to the struct field so `json.Unmarshal` parses the string into an integer automatically.

Deterministic, non-destructive resolution

Code Standard: Bad Pattern vs Verified Fix

Live Syntax
Anti-Pattern vs Verified Fix
1// ❌ Bad: Strict integer type crashes on string data
2type User struct {
3 Age int `json:"age"`
4}
5
6// ✅ Good: Using the string tag for automatic coercion
7type User struct {
8 Age int `json:"age,string"`
9}

Test and resolve this using JSON to Go Struct

Execute directly in your browser memory. Zero API keys, zero network tracking, completely client-side.

Launch JSON to Go Struct

Frequently Asked Questions

Q:What if the JSON field is sometimes a number and sometimes a string?

The ,string tag only works if the JSON value is ALWAYS a string. For mixed types, unmarshal into an interface{} or a custom UnmarshalJSON type.

Q:How can I generate structs automatically?

Use our JSON to Go Struct tool to generate accurate structs with tags from your payloads.