How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Go · Go

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

goroutine 1 [running]: runtime/debug.Stack() /usr/local/go/src/runtime/debug/stack.go:24 +0x5e main.loadConfig() /app/config/config.go:22 +0x1a4 encoding/json.(*decodeState).unmarshal(0x14000196040, {0x102850ea0, 0x14000196060}) /usr/local/go/src/encoding/json/decode.go:181 +0x148 encoding/json.Unmarshal({0x14000116420, 0x4f}, {0x102850ea0, 0x14000196060}) /usr/local/go/src/encoding/json/decode.go:108 +0xb8 main.main() /app/main.go:15 +0x94

Here's what each line means:

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.

Before (broken)
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
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Run go test ./... locally to confirm JSON parsing handles all formats.
  2. Open a pull request with the unmarshal changes.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. 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.