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

json.% generates invalid json for NaN, Inf #18007

Closed
timotheecour opened this issue May 14, 2021 · 0 comments · Fixed by #18026
Closed

json.% generates invalid json for NaN, Inf #18007

timotheecour opened this issue May 14, 2021 · 0 comments · Fixed by #18026

Comments

@timotheecour
Copy link
Member

timotheecour commented May 14, 2021

Example

when true: # D20210513T172224:here
  import std/json
  let a = [NaN, Inf, -Inf, 0.0, -0.0, 1e20, 1.5]
  let j = %a
  echo j # prints: `[nan,inf,-inf,0.0,-0.0,1e+20,1.5]`, which is invalid json (eg will fail in js console with `JSON.stringify('[nan,inf,-inf,0.0,-0.0,1e+20,1.5]')`)
  let j2 = $j
  let j3 = j2.parseJson # errors (as it should): Error: unhandled exception: input(1, 4) Error: { expected [JsonParsingError]

Current Output

see comments

Expected Output

produce valid json

Possible Solution 1

NaN, Inf,-Inf could use newJRawNumber mechanism we added recently, but this may still lead to an ambiguity when interpreting nan for eg, as this could either mean a string nan or a number nan.

We should at least ensure roundtrip property, so that Inf => "inf" => Inf

Possible Solution 2

cast the Inf/-Inf/NaN to uint first, which would have other benefits (eg preserving bit pattern for nan so that nan value is preserved)

But this should be handled transparently for serialization/deserialization purposes

Additional Information

1.5.1 1e080eb
also affects jsonutils, which reuses json.% for this part
similar to https://perlmaven.com/parsing-nan-in-json (see also https://stackoverflow.com/questions/6601812/sending-nan-in-json)

timotheecour added a commit to timotheecour/Nim that referenced this issue May 16, 2021
Araq pushed a commit that referenced this issue May 16, 2021
…f invalid json (#18026)

* fix #18007: std/json now serializes nan,inf,-inf as raw strings instead of invalid json

* fix roundtrip

* fix tests

* fix changelog

* simplify

* add runnableExamples

* fix typo [skip ci]
PMunch pushed a commit to PMunch/Nim that referenced this issue Mar 28, 2022
…nstead of invalid json (nim-lang#18026)

* fix nim-lang#18007: std/json now serializes nan,inf,-inf as raw strings instead of invalid json

* fix roundtrip

* fix tests

* fix changelog

* simplify

* add runnableExamples

* fix typo [skip ci]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant