Skip to content

Infinity handling differs to python native json #80

@telegraphic

Description

@telegraphic

It looks like ujson handles infinity different to the native json encoder:

import ujson, json, numpy

a = np.array([1,2,3,4,numpy.inf])
b = json.dumps({"test" : a.tolist()})
# outputs '{"test": [1,2,3,4,5, Infinity]}'
b= ujson.dumps({"test" : a.tolist()})
# raises OverflowError: Invalid Inf value when encoding double

Similarly, an Overflow error is raised when NaN is encountered. It seems the relevant lines are 499-508 in ultrajsonenc.c:

    if (value == HUGE_VAL || value == -HUGE_VAL)
    {
        SetError (obj, enc, "Invalid Inf value when encoding double");
        return FALSE;
    }
    if (! (value == value)) 
    {
        SetError (obj, enc, "Invalid Nan value when encoding double");
        return FALSE;
    }

In the interests of keeping ujson as a drop-in replacement for json, may I suggest this is changed so that it converts the NaN / Infinity to strings (like json) and doesn't raise an error? The decoder would likely need to be changed too...

Cheers
Dan

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions