Fix JsonUnmarshalError: json: cannot unmarshal string into Go struct field Config.port of type int in Go
This error occurs when encoding/json tries to decode a JSON value into a Go struct field of an incompatible type, such as a string into an int field. Fix it by either correcting the JSON source to send the right type, using json.Number for flexible numeric parsing, or implementing a custom UnmarshalJSON method on the struct.
Reading the Stack Trace
Here's what each line means:
- main.loadConfig() /app/config/config.go:22 +0x1a4: The loadConfig function at line 22 reads and unmarshals a JSON config file that contains a type mismatch.
- encoding/json.Unmarshal({0x14000116420, 0x4f}, {0x102850ea0, 0x14000196060}): encoding/json.Unmarshal encounters a string value for a field declared as int and returns an UnmarshalTypeError.
- encoding/json.(*decodeState).unmarshal(0x14000196040, {0x102850ea0, 0x14000196060}): The internal decoder state machine cannot convert the JSON string token to the target Go int type.
Common Causes
1. JSON source sends numbers as strings
The JSON file or API response wraps numeric values in quotes, making them strings instead of numbers.
// config.json: {"port": "8080", "workers": "4"}
type Config struct {
Port int `json:"port"`
Workers int `json:"workers"`
}
func loadConfig() (*Config, error) {
data, _ := os.ReadFile("config.json")
var cfg Config
err := json.Unmarshal(data, &cfg) // fails: "8080" is a string, not int
return &cfg, err
}
2. Null JSON value into non-pointer field
The JSON contains null for a field declared as a non-pointer type, causing an unmarshal error.
// JSON: {"name": "app", "port": null}
type Config struct {
Name string `json:"name"`
Port int `json:"port"` // null cannot unmarshal into int
}
3. Array received where object expected
The API response structure changed from an object to an array, breaking the unmarshal target type.
type Response struct {
Data User `json:"data"` // expects object
}
// API now returns: {"data": [{...}, {...}]} — array, not object
The Fix
Implement a custom UnmarshalJSON method that uses json.Number for flexible numeric parsing. This handles both quoted strings and raw numbers from JSON sources. Add proper error wrapping for clear diagnostics.
type Config struct {
Port int `json:"port"`
Workers int `json:"workers"`
}
func loadConfig() (*Config, error) {
data, _ := os.ReadFile("config.json")
var cfg Config
err := json.Unmarshal(data, &cfg)
return &cfg, err
}
type Config struct {
Port int `json:"port"`
Workers int `json:"workers"`
}
func (c *Config) UnmarshalJSON(data []byte) error {
type raw struct {
Port json.Number `json:"port"`
Workers json.Number `json:"workers"`
}
var r raw
if err := json.Unmarshal(data, &r); err != nil {
return fmt.Errorf("parsing config: %w", err)
}
port, err := r.Port.Int64()
if err != nil {
return fmt.Errorf("invalid port value %q: %w", r.Port, err)
}
c.Port = int(port)
workers, err := r.Workers.Int64()
if err != nil {
return fmt.Errorf("invalid workers value %q: %w", r.Workers, err)
}
c.Workers = int(workers)
return nil
}
func loadConfig() (*Config, error) {
data, err := os.ReadFile("config.json")
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("unmarshaling config: %w", err)
}
return &cfg, nil
}
Testing the Fix
package config_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestConfig_NumericStrings(t *testing.T) {
data := []byte(`{"port": "8080", "workers": "4"}`)
var cfg Config
err := json.Unmarshal(data, &cfg)
assert.NoError(t, err)
assert.Equal(t, 8080, cfg.Port)
assert.Equal(t, 4, cfg.Workers)
}
func TestConfig_RawNumbers(t *testing.T) {
data := []byte(`{"port": 8080, "workers": 4}`)
var cfg Config
err := json.Unmarshal(data, &cfg)
assert.NoError(t, err)
assert.Equal(t, 8080, cfg.Port)
}
func TestConfig_InvalidPort(t *testing.T) {
data := []byte(`{"port": "not-a-number", "workers": 4}`)
var cfg Config
err := json.Unmarshal(data, &cfg)
assert.Error(t, err)
assert.Contains(t, err.Error(), "invalid port")
}
Run your tests:
go test ./config/... -v
Pushing Through CI/CD
git checkout -b fix/go-json-unmarshal-error,git add config/config.go config/config_test.go,git commit -m "fix: use json.Number to handle numeric strings in config parsing",git push origin fix/go-json-unmarshal-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm JSON parsing handles all formats.
- Open a pull request with the unmarshal changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify in staging.
Frequently Asked Questions
BugStack tests with various JSON formats including numeric strings, raw numbers, nulls, and invalid values, and validates that all parsing produces correct results before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Use json.Number when you need to handle both string and numeric JSON values for the same field. Use custom UnmarshalJSON when you need complex parsing logic.
By default, encoding/json silently ignores unknown fields. Use json.Decoder with DisallowUnknownFields() to reject them, which helps catch API contract mismatches early.