Skip to content

Bugfix: do not generate invalid JSON when float value is +Inf, -Inf or NaN #421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

dmitrybarsukov
Copy link

This PR solves issue #134 - Invalid JSON generated for NaN and Inf.

Context:
The following code generates invalid JSON, which cannot be unmarshalled either via easyjson or builtin go encoding/json package.

package main

import (
	"fmt"
	"math"
)

//go:generate easyjson $GOFILE

//easyjson:json
type Struct struct {
	Float1 float64
	Float2 float64
	Float3 float64
}

func main() {
	s := Struct{
		Float1: math.NaN(),
		Float2: math.Inf(1),
		Float3: math.Inf(-1),
	}
	b, err := s.MarshalJSON()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(b))
	var s2 Struct

	if err := s2.UnmarshalJSON(b); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(s2)
}

Output:

{"Float1":NaN,"Float2":+Inf,"Float3":-Inf}
parse error: syntax error near offset 10 of 'NaN,"Float...'

Suggested solution:

In jwriter/writer.go: check floats for NaN, +Inf, -Inf values before passing them into strconv.AppendFloat, and write w.Error = "json: unsupported value: ..." if it is so

@dmitrybarsukov dmitrybarsukov force-pushed the bugfix/invalid-json-on-NaN-or-Inf branch from 107d1db to 31b2360 Compare May 25, 2025 21:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant