← index #3511PR #5138
Duplicate · high · value 0.719
QUERY · ISSUE

ujson dumps NaN but doesn't load it

openby stinosopened 2017-12-21updated 2024-09-29
enhancement

The mod_ujson_load function doesn't handle nan though it is a valid representation:

>>> import ujson
>>> ujson.dumps(float('nan'))
'nan'
>>> ujson.loads(ujson.dumps(float('nan')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: syntax error in JSON

Quick hack to solve this (sorry couldn't immediately figure out how to get the nan constant), line 115 in modujson.c:

                } else if (S_CUR(s) == 'a' && S_NEXT(s) == 'n') {
                    S_NEXT(s);
                    next = mp_parse_num_decimal("nan", 3, false, false, NULL);
CANDIDATE · PULL REQUEST

extmod/ujson: Add support for CPython-compatible nan/inf handling.

openby stinosopened 2019-09-23updated 2021-10-18
enhancementextmod

Modify the JSON loading code so it can parse the JavaScript floating
point representations NaN/Infinity/-Infinity, and support the allow_nan
keyword argument for dump() and dumps() which controls whether those
representations get created or else lead to raising a ValueError.
All of this is the same as CPython's implementation and when enabled
fixes the inconsistency in the current code which unconditionally
creates lowercase nan/inf strings but doesn't parse them.

This is a fix for #3511. It requires more changes than I initially anticipated, but I don't see another way than to pass the needed information into float_print via the mp_print_kind argument.
Also needs quite some extra code, enabled by default for a couple of ports but that was mainly to get CI feedback.
Flag is called MICROPY_PY_UJSON_ALLOWNAN but it's essentially about CPython compatibility so another name might be more suitable.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied