Skip to content

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

Merged
rvasily merged 1 commit intomailru:masterfrom
dmitrybarsukov:bugfix/invalid-json-on-NaN-or-Inf
Sep 15, 2025
Merged

Bugfix: do not generate invalid JSON when float value is +Inf, -Inf or NaN#421
rvasily merged 1 commit intomailru:masterfrom
dmitrybarsukov:bugfix/invalid-json-on-NaN-or-Inf

Conversation

@dmitrybarsukov
Copy link
Copy Markdown
Contributor

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
@rvasily rvasily merged commit ef22ec5 into mailru:master Sep 15, 2025
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.

2 participants