]> Cypherpunks repositories - gostls13.git/commit
encoding/json/v2: fix incorrect marshaling of NaN in float64 any
authorJoe Tsai <joetsai@digital-static.net>
Tue, 12 Aug 2025 08:56:43 +0000 (01:56 -0700)
committerJoseph Tsai <joetsai@digital-static.net>
Wed, 13 Aug 2025 22:47:31 +0000 (15:47 -0700)
commitaf8870708bbaf15956a27cbab15582b4c666855e
treef60725fc5fcc77431142aff96c04fbe53f50c1a8
parent0a75e5a07b858cbe6216c99fa12d582d063499d9
encoding/json/v2: fix incorrect marshaling of NaN in float64 any

There is a fast-path optimization for marshaling an any type
that should be semantically identical to when the optimization
is not active (i.e., optimizeCommon is false).
Unfortunately, the optimization accidentally allows NaN,
which this change fixes.

The source of this discrepency is that Encoder.WriteToken(Float(math.NaN()))
emits a JSON string with "NaN", rather than report an error.
The rationale for this behavior is because we needed to decide what to do
with Float(math.NaN()), whether it would return an error, panic, or allow it.
To keep the API simpler (no errors) and less sharp (no panics), we permitted NaN.
The fact that WriteToken allowed it is a logical extension of that decision,
but we could decide to disallow it at least within WriteToken.
As things stand, it is already inconsistent between json/v2 and jsontext, where
json/v2 rejects NaN by default in Marshal, but jsontext allows it in WriteToken.

This only modifies code that is compiled under goexperiment.jsonv2.

Fixes #74797

Change-Id: Ib0708cfbf93c2b059c0a85e4c4544c0604573448
Reviewed-on: https://go-review.googlesource.com/c/go/+/695276
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
src/encoding/json/v2/arshal_any.go
src/encoding/json/v2/arshal_test.go