Return a JSON string representation of a Python data structure. >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'
(self, o)
| 344 | raise TypeError(repr(o) + " is not JSON serializable") |
| 345 | |
| 346 | def encode(self, o): |
| 347 | """Return a JSON string representation of a Python data structure. |
| 348 | |
| 349 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 350 | '{"foo": ["bar", "baz"]}' |
| 351 | |
| 352 | """ |
| 353 | # This is for extremely simple cases and benchmarks. |
| 354 | if isinstance(o, basestring): |
| 355 | if isinstance(o, str): |
| 356 | _encoding = self.encoding |
| 357 | if (_encoding is not None |
| 358 | and not (_encoding == 'utf-8')): |
| 359 | o = o.decode(_encoding) |
| 360 | if self.ensure_ascii: |
| 361 | return encode_basestring_ascii(o) |
| 362 | else: |
| 363 | return encode_basestring(o) |
| 364 | # This doesn't pass the iterator directly to ''.join() because the |
| 365 | # exceptions aren't as detailed. The list call should be roughly |
| 366 | # equivalent to the PySequence_Fast that ''.join() would do. |
| 367 | chunks = list(self.iterencode(o)) |
| 368 | return ''.join(chunks) |
| 369 | |
| 370 | def iterencode(self, o): |
| 371 | """Encode the given object and yield each string representation as |