Skip to content

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