Json Int64 Overflow Decode Error

Decode MaxInt64+1 into an int64 field to get UnmarshalTypeError, while the uint64 field beside it accepts the same number.

GoData Integrity

Code

gosnippet
30 lines
package main

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

type Session struct {
	UserID   int64  `json:"user_id"`
	LeaderID uint64 `json:"leader_id"`
}

func main() {
	// 9223372036854775808 = MaxInt64 + 1: overflow for int64, fits uint64
	payload := []byte(`{"user_id":9223372036854775808,"leader_id":9223372036854775808}`)

	var session Session
	err := json.Unmarshal(payload, &session)

	var typeErr *json.UnmarshalTypeError
	fmt.Println("decode error:", errors.As(err, &typeErr))
	if typeErr != nil {
		fmt.Printf("field %s value %s does not fit %s\n", typeErr.Field, typeErr.Value, typeErr.Type)
	}

	// the rejected field stays zero; the representable one decodes anyway
	fmt.Println("user_id:", session.UserID)
	fmt.Println("leader_id:", session.LeaderID)
}

How the steps land

Json Int64 Overflow Decode Error keeps everything in the function main.

Applying it

The run emits 4 labeled sections — decode error:, field, user_id:, leader_id: — one per step.

Statements that matter

payload := []byte(`{"user_id":9223372036854775808,"leader_id":9223372036854775808}`)

Interactive Tools for This Topic

FAQ

What does Json Int64 Overflow Decode Error print when run?
Running the file directly is enough — expect labeled output lines such as `decode error:`, `field`, `user_id:`.