Also updated an example for default() in the module docstring.
Removed quotes around type name in other error messages.
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
- ... raise TypeError(repr(obj) + " is not JSON serializable")
+ ... raise TypeError(f'Object of type {obj.__class__.__name__} '
+ ... f'is not JSON serializable')
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
- raise TypeError('the JSON object must be str, bytes or bytearray, '
- 'not {!r}'.format(s.__class__.__name__))
+ raise TypeError(f'the JSON object must be str, bytes or bytearray, '
+ f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')
if (cls is None and object_hook is None and
return JSONEncoder.default(self, o)
"""
- raise TypeError("Object of type '%s' is not JSON serializable" %
- o.__class__.__name__)
+ raise TypeError(f'Object of type {o.__class__.__name__} '
+ f'is not JSON serializable')
def encode(self, o):
"""Return a JSON string representation of a Python data structure.
elif _skipkeys:
continue
else:
- raise TypeError("key " + repr(key) + " is not a string")
+ raise TypeError(f'keys must be str, int, float, bool or None, '
+ f'not {key.__class__.__name__}')
if first:
first = False
else:
def test_non_string_keys_dict(self):
data = {'a' : 1, (1, 2) : 2}
+ with self.assertRaisesRegex(TypeError,
+ 'keys must be str, int, float, bool or None, not tuple'):
+ self.dumps(data)
- #This is for c encoder
- self.assertRaises(TypeError, self.dumps, data)
-
- #This is for python encoder
- self.assertRaises(TypeError, self.dumps, data, indent=True)
+ def test_not_serializable(self):
+ import sys
+ with self.assertRaisesRegex(TypeError,
+ 'Object of type module is not JSON serializable'):
+ self.dumps(sys)
def test_truncated_input(self):
test_cases = [
continue;
}
else {
- /* TODO: include repr of key */
- PyErr_SetString(PyExc_TypeError, "keys must be a string");
+ PyErr_Format(PyExc_TypeError,
+ "keys must be str, int, float, bool or None, "
+ "not %.100s", key->ob_type->tp_name);
goto bail;
}