Return a JSON string representation of a Python data structure. >>> from simplejson import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'
(self, o)
| 213 | raise TypeError(repr(o) + " is not JSON serializable") |
| 214 | |
| 215 | def encode(self, o): |
| 216 | """Return a JSON string representation of a Python data structure. |
| 217 | |
| 218 | >>> from simplejson import JSONEncoder |
| 219 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) |
| 220 | '{"foo": ["bar", "baz"]}' |
| 221 | |
| 222 | """ |
| 223 | # This is for extremely simple cases and benchmarks. |
| 224 | if isinstance(o, basestring): |
| 225 | if isinstance(o, str): |
| 226 | _encoding = self.encoding |
| 227 | if (_encoding is not None |
| 228 | and not (_encoding == 'utf-8')): |
| 229 | o = o.decode(_encoding) |
| 230 | if self.ensure_ascii: |
| 231 | return encode_basestring_ascii(o) |
| 232 | else: |
| 233 | return encode_basestring(o) |
| 234 | # This doesn't pass the iterator directly to ''.join() because the |
| 235 | # exceptions aren't as detailed. The list call should be roughly |
| 236 | # equivalent to the PySequence_Fast that ''.join() would do. |
| 237 | chunks = self.iterencode(o, _one_shot=True) |
| 238 | if not isinstance(chunks, (list, tuple)): |
| 239 | chunks = list(chunks) |
| 240 | if self.ensure_ascii: |
| 241 | return ''.join(chunks) |
| 242 | else: |
| 243 | return u''.join(chunks) |
| 244 | |
| 245 | def iterencode(self, o, _one_shot=False): |
| 246 | """Encode the given object and yield each string |