Skip to content

fix: encode NaN/Inf floats as null in JSON encoder#1553

Open
toller892 wants to merge 1 commit into
uber-go:masterfrom
toller892:fix/json-encoder-nan-inf-null
Open

fix: encode NaN/Inf floats as null in JSON encoder#1553
toller892 wants to merge 1 commit into
uber-go:masterfrom
toller892:fix/json-encoder-nan-inf-null

Conversation

@toller892

Copy link
Copy Markdown

Problem

The JSON encoder encodes NaN, +Inf, and -Inf as quoted strings ("NaN", "+Inf", "-Inf"), producing invalid JSON. This is inconsistent with Go's encoding/json, which returns an UnsupportedValueError for these values.

// Current behavior:
enc.AddFloat64("k", math.NaN())  // outputs: "k":"NaN"   (string, not a number)
enc.AddFloat64("k", math.Inf(1)) // outputs: "k":"+Inf"  (string, not a number)

This means:

  1. zap.Reflect() with a struct containing NaN returns an error, but enc.AddFloat64() silently produces a string — inconsistent behavior within zap itself.
  2. The output is not valid JSON — "NaN" is a string, not a numeric value.
  3. Consumers parsing zap's JSON output cannot distinguish between a legitimate string field and a mis-encoded float.

Fix

Encode NaN, +Inf, and -Inf as null in the JSON encoder. null is valid JSON and the most common representation for non-finite numbers in JSON serializers.

// After fix:
enc.AddFloat64("k", math.NaN())  // outputs: "k":null
enc.AddFloat64("k", math.Inf(1)) // outputs: "k":null
enc.AddFloat64("k", math.Inf(-1))// outputs: "k":null

Changes

  • zapcore/json_encoder.go: Change appendFloat() to emit null instead of "NaN"/"+Inf"/"-Inf"
  • zapcore/json_encoder_impl_test.go: Update test expectations for NaN/Inf float64 and float32 cases

Fixes #690

The JSON encoder previously encoded NaN, +Inf, and -Inf as quoted
strings ("NaN", "+Inf", "-Inf"), producing invalid JSON. This was
inconsistent with Go's encoding/json, which returns an error for these
values.

Encode these special float values as null instead, which is valid JSON
and the most common representation for non-finite numbers.

Fixes uber-go#690
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

float NaN are encoded as string "NaN"

3 participants