Return a JSON string representation of a Python data structure. >>> from simplejson import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'
(self, o)
| 290 | o.__class__.__name__) |
| 291 | |
| 292 | def encode(self, o): |
| 293 | """Return a JSON string representation of a Python data structure. |
| 294 | |
| 295 | >>> from simplejson import JSONEncoder |
| 296 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 297 | '{"foo": ["bar", "baz"]}' |
| 298 | |
| 299 | """ |
| 300 | # This is for extremely simple cases and benchmarks. |
| 301 | if isinstance(o, binary_type): |
| 302 | _encoding = self.encoding |
| 303 | if (_encoding is not None and not (_encoding == 'utf-8')): |
| 304 | o = text_type(o, _encoding) |
| 305 | if isinstance(o, string_types): |
| 306 | if self.ensure_ascii: |
| 307 | return encode_basestring_ascii(o) |
| 308 | else: |
| 309 | return encode_basestring(o) |
| 310 | # This doesn't pass the iterator directly to ''.join() because the |
| 311 | # exceptions aren't as detailed. The list call should be roughly |
| 312 | # equivalent to the PySequence_Fast that ''.join() would do. |
| 313 | chunks = self.iterencode(o) |
| 314 | if not isinstance(chunks, (list, tuple)): |
| 315 | chunks = list(chunks) |
| 316 | if self.ensure_ascii: |
| 317 | return ''.join(chunks) |
| 318 | else: |
| 319 | return u''.join(chunks) |
| 320 | |
| 321 | def iterencode(self, o): |
| 322 | """Encode the given object and yield each string |