[docs] [issue14674] Add link to RFC 4627 from json documentation

Chris Rebert report at bugs.python.org
Tue May 15 10:22:12 CEST 2012

Chris Rebert <pybugs at rebertia.com> added the comment:

The "import json"s were left for uniformity with the other code samples in the module's docs.

Also, here's what the pedantically-strict recipes might look like:

def _reject_inf_nan(string):
    if string in {'-Infinity', 'Infinity', 'NaN'}:
        raise ValueError("JSON does not allow infinite or NaN number values")

def _reject_dupe_keys(pairs):
    obj = {}
    for key, value in pairs:
        if key in pairs:
            raise ValueError("Name %s repeated in an object" % repr(key))
        obj[key] = value
    return obj

def strict_loads(string):
    result = loads(string, parse_constant=_reject_inf_nan, object_pairs_hook=_reject_dupe_keys)
    if not isinstance(result, (dict, list)):
        raise ValueError("The top-level entity of the JSON text was not an object or an array")
    return result

def strict_dumps(obj):
    if not isinstance(obj, (dict, list)):
        raise TypeError("The top-level object of a JSON text must be a dict or a list")
    return dumps(obj, allow_nan=False)


Python tracker <report at bugs.python.org>

More information about the docs mailing list