Message 160693 - Python tracker (original) (raw)

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)