Skip to content

Commit

Permalink
Fix encoding of infinity (#80).
Browse files Browse the repository at this point in the history
Infinity was being encoded as 'Inf' which, whilst the JSON spec doesn't include
any non-finite floats, differs from the conventions in other JSON libraries,
JavaScript of using 'Infinity'. It also differs from what `ujson.loads()`
expects so that `ujson.loads(ujson.dumps(math.inf))` raises an exception.

Closes #80.
  • Loading branch information
bwoodsend committed Aug 8, 2022
1 parent bcdc041 commit b18f60d
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion python/objToJSON.c
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,7 @@ PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)

if (encoder.allowNan)
{
csInf = "Inf";
csInf = "Infinity";
csNan = "NaN";
}

Expand Down
2 changes: 1 addition & 1 deletion python/ujson.c
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ PyObject* JSONDecodeError;
#define ENCODER_HELP_TEXT "Use ensure_ascii=false to output UTF-8. " \
"Set encode_html_chars=True to encode < > & as unicode escape sequences. "\
"Set escape_forward_slashes=False to prevent escaping / characters." \
"Set allow_nan=False to raise an exception when NaN or Inf would be serialized." \
"Set allow_nan=False to raise an exception when NaN or Infinity would be serialized." \
"Set reject_bytes=True to raise TypeError on bytes."

static PyMethodDef ujsonMethods[] = {
Expand Down
4 changes: 2 additions & 2 deletions tests/test_ujson.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,8 +842,8 @@ def test_encode_no_assert(test_input):
(1.0, "1.0"),
(OrderedDict([(1, 1), (0, 0), (8, 8), (2, 2)]), '{"1":1,"0":0,"8":8,"2":2}'),
({"a": float("NaN")}, '{"a":NaN}'),
({"a": float("inf")}, '{"a":Inf}'),
({"a": -float("inf")}, '{"a":-Inf}'),
({"a": float("inf")}, '{"a":Infinity}'),
({"a": -float("inf")}, '{"a":-Infinity}'),
],
)
def test_encode(test_input, expected):
Expand Down

0 comments on commit b18f60d

Please sign in to comment.