Skip to content
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

close #18009 parseJson JInt vs JFloat; preserve -0.0 as JFloat to distinguish from 0.0 #18067

Merged
merged 1 commit into from
May 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ when defined(js):
of "[object Array]": return JArray
of "[object Object]": return JObject
of "[object Number]":
if isInteger(x):
if isInteger(x) and 1.0 / cast[float](x) != -Inf: # preserve -0.0 as float
timotheecour marked this conversation as resolved.
Show resolved Hide resolved
if isSafeInteger(x):
return JInt
else:
Expand Down
17 changes: 16 additions & 1 deletion tests/stdlib/tjsonutils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ discard """

import std/jsonutils
import std/json
from std/math import isNaN
from std/math import isNaN, signbit
from stdtest/testutils import whenRuntimeJs

proc testRoundtrip[T](t: T, expected: string) =
# checks that `T => json => T2 => json2` is such that json2 = json
Expand Down Expand Up @@ -123,6 +124,20 @@ template fn() =
testRoundtripVal((Inf, -Inf, 0.0, -0.0, 1.0)): """["inf","-inf",0.0,-0.0,1.0]"""
doAssert ($NaN.toJson).parseJson.jsonTo(float).isNaN

block: # bug #18009; unfixable unless we change parseJson (which would have overhead),
# but at least we can guarantee that the distinction between 0.0 and -0.0 is preserved.
let a = (0, 0.0, -0.0, 0.5, 1, 1.0)
testRoundtripVal(a): "[0,0.0,-0.0,0.5,1,1.0]"
let a2 = $($a.toJson).parseJson
whenRuntimeJs:
doAssert a2 == "[0,0,-0.0,0.5,1,1]"
do:
doAssert a2 == "[0,0.0,-0.0,0.5,1,1.0]"
let b = a2.parseJson.jsonTo(type(a))
doAssert not b[1].signbit
doAssert b[2].signbit
doAssert not b[3].signbit

block: # case object
type Foo = object
x0: float
Expand Down