@@ -13,7 +13,7 @@ def _import_speedups():
1313
1414from simplejson .decoder import PosInf
1515
16- ESCAPE = re .compile (r '[\x00-\x1f\\"\b\f\n\r\t]' )
16+ ESCAPE = re .compile (ur '[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029 ]' )
1717ESCAPE_ASCII = re .compile (r'([\\"]|[^\ -~])' )
1818HAS_UTF8 = re .compile (r'[\x80-\xff]' )
1919ESCAPE_DCT = {
@@ -24,6 +24,8 @@ def _import_speedups():
2424 '\n ' : '\\ n' ,
2525 '\r ' : '\\ r' ,
2626 '\t ' : '\\ t' ,
27+ u'\u2028 ' : '\\ u2028' ,
28+ u'\u2029 ' : '\\ u2029' ,
2729}
2830for i in range (0x20 ):
2931 #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
@@ -78,7 +80,7 @@ class JSONEncoder(object):
7880 +-------------------+---------------+
7981 | Python | JSON |
8082 +===================+===============+
81- | dict | object |
83+ | dict, namedtuple | object |
8284 +-------------------+---------------+
8385 | list, tuple | array |
8486 +-------------------+---------------+
@@ -104,7 +106,8 @@ class JSONEncoder(object):
104106 def __init__ (self , skipkeys = False , ensure_ascii = True ,
105107 check_circular = True , allow_nan = True , sort_keys = False ,
106108 indent = None , separators = None , encoding = 'utf-8' , default = None ,
107- use_decimal = False ):
109+ use_decimal = True , namedtuple_as_object = True ,
110+ tuple_as_array = True ):
108111 """Constructor for JSONEncoder, with sensible defaults.
109112
110113 If skipkeys is false, then it is a TypeError to attempt
@@ -152,6 +155,11 @@ def __init__(self, skipkeys=False, ensure_ascii=True,
152155 be supported directly by the encoder. For the inverse, decode JSON
153156 with ``parse_float=decimal.Decimal``.
154157
158+ If namedtuple_as_object is true (the default), tuple subclasses with
159+ ``_asdict()`` methods will be encoded as JSON objects.
160+
161+ If tuple_as_array is true (the default), tuple (and subclasses) will
162+ be encoded as JSON arrays.
155163 """
156164
157165 self .skipkeys = skipkeys
@@ -160,6 +168,8 @@ def __init__(self, skipkeys=False, ensure_ascii=True,
160168 self .allow_nan = allow_nan
161169 self .sort_keys = sort_keys
162170 self .use_decimal = use_decimal
171+ self .namedtuple_as_object = namedtuple_as_object
172+ self .tuple_as_array = tuple_as_array
163173 if isinstance (indent , (int , long )):
164174 indent = ' ' * indent
165175 self .indent = indent
@@ -274,12 +284,14 @@ def floatstr(o, allow_nan=self.allow_nan,
274284 _iterencode = c_make_encoder (
275285 markers , self .default , _encoder , self .indent ,
276286 self .key_separator , self .item_separator , self .sort_keys ,
277- self .skipkeys , self .allow_nan , key_memo , self .use_decimal )
287+ self .skipkeys , self .allow_nan , key_memo , self .use_decimal ,
288+ self .namedtuple_as_object , self .tuple_as_array )
278289 else :
279290 _iterencode = _make_iterencode (
280291 markers , self .default , _encoder , self .indent , floatstr ,
281292 self .key_separator , self .item_separator , self .sort_keys ,
282- self .skipkeys , _one_shot , self .use_decimal )
293+ self .skipkeys , _one_shot , self .use_decimal ,
294+ self .namedtuple_as_object , self .tuple_as_array )
283295 try :
284296 return _iterencode (o , 0 )
285297 finally :
@@ -315,7 +327,7 @@ def iterencode(self, o, _one_shot=False):
315327
316328def _make_iterencode (markers , _default , _encoder , _indent , _floatstr ,
317329 _key_separator , _item_separator , _sort_keys , _skipkeys , _one_shot ,
318- _use_decimal ,
330+ _use_decimal , _namedtuple_as_object , _tuple_as_array ,
319331 ## HACK: hand-optimized bytecode; turn globals into locals
320332 False = False ,
321333 True = True ,
@@ -373,7 +385,13 @@ def _iterencode_list(lst, _current_indent_level):
373385 yield buf + str (value )
374386 else :
375387 yield buf
376- if isinstance (value , (list , tuple )):
388+ if isinstance (value , list ):
389+ chunks = _iterencode_list (value , _current_indent_level )
390+ elif (_namedtuple_as_object and isinstance (value , tuple ) and
391+ hasattr (value , '_asdict' )):
392+ chunks = _iterencode_dict (value ._asdict (),
393+ _current_indent_level )
394+ elif _tuple_as_array and isinstance (value , tuple ):
377395 chunks = _iterencode_list (value , _current_indent_level )
378396 elif isinstance (value , dict ):
379397 chunks = _iterencode_dict (value , _current_indent_level )
@@ -452,7 +470,13 @@ def _iterencode_dict(dct, _current_indent_level):
452470 elif _use_decimal and isinstance (value , Decimal ):
453471 yield str (value )
454472 else :
455- if isinstance (value , (list , tuple )):
473+ if isinstance (value , list ):
474+ chunks = _iterencode_list (value , _current_indent_level )
475+ elif (_namedtuple_as_object and isinstance (value , tuple ) and
476+ hasattr (value , '_asdict' )):
477+ chunks = _iterencode_dict (value ._asdict (),
478+ _current_indent_level )
479+ elif _tuple_as_array and isinstance (value , tuple ):
456480 chunks = _iterencode_list (value , _current_indent_level )
457481 elif isinstance (value , dict ):
458482 chunks = _iterencode_dict (value , _current_indent_level )
@@ -480,7 +504,14 @@ def _iterencode(o, _current_indent_level):
480504 yield str (o )
481505 elif isinstance (o , float ):
482506 yield _floatstr (o )
483- elif isinstance (o , (list , tuple )):
507+ elif isinstance (o , list ):
508+ for chunk in _iterencode_list (o , _current_indent_level ):
509+ yield chunk
510+ elif (_namedtuple_as_object and isinstance (o , tuple ) and
511+ hasattr (o , '_asdict' )):
512+ for chunk in _iterencode_dict (o ._asdict (), _current_indent_level ):
513+ yield chunk
514+ elif (_tuple_as_array and isinstance (o , tuple )):
484515 for chunk in _iterencode_list (o , _current_indent_level ):
485516 yield chunk
486517 elif isinstance (o , dict ):
0 commit comments