home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 May / maximum-cd-2010-05.iso / DiscContents / boxee-0.9.20.10711.exe / system / python / local / simplejson / encoder.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-02  |  13.3 KB  |  460 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. '''Implementation of JSONEncoder
  5. '''
  6. import re
  7.  
  8. try:
  9.     from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
  10. except ImportError:
  11.     c_encode_basestring_ascii = None
  12.  
  13.  
  14. try:
  15.     from simplejson._speedups import make_encoder as c_make_encoder
  16. except ImportError:
  17.     c_make_encoder = None
  18.  
  19. ESCAPE = re.compile('[\\x00-\\x1f\\\\"\\b\\f\\n\\r\\t]')
  20. ESCAPE_ASCII = re.compile('([\\\\"]|[^\\ -~])')
  21. HAS_UTF8 = re.compile('[\\x80-\\xff]')
  22. ESCAPE_DCT = {
  23.     '\\': '\\\\',
  24.     '"': '\\"',
  25.     '\x08': '\\b',
  26.     '\x0c': '\\f',
  27.     '\n': '\\n',
  28.     '\r': '\\r',
  29.     '\t': '\\t' }
  30. for i in range(32):
  31.     ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
  32.  
  33. INFINITY = float('1e66666')
  34. FLOAT_REPR = repr
  35.  
  36. def encode_basestring(s):
  37.     '''Return a JSON representation of a Python string
  38.  
  39.     '''
  40.     
  41.     def replace(match):
  42.         return ESCAPE_DCT[match.group(0)]
  43.  
  44.     return '"' + ESCAPE.sub(replace, s) + '"'
  45.  
  46.  
  47. def py_encode_basestring_ascii(s):
  48.     '''Return an ASCII-only JSON representation of a Python string
  49.  
  50.     '''
  51.     if isinstance(s, str) and HAS_UTF8.search(s) is not None:
  52.         s = s.decode('utf-8')
  53.     
  54.     
  55.     def replace(match):
  56.         s = match.group(0)
  57.         
  58.         try:
  59.             return ESCAPE_DCT[s]
  60.         except KeyError:
  61.             n = ord(s)
  62.             if n < 65536:
  63.                 return '\\u%04x' % (n,)
  64.             else:
  65.                 n -= 65536
  66.                 s1 = 55296 | n >> 10 & 1023
  67.                 s2 = 56320 | n & 1023
  68.                 return '\\u%04x\\u%04x' % (s1, s2)
  69.         except:
  70.             n < 65536
  71.  
  72.  
  73.     return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
  74.  
  75. if not c_encode_basestring_ascii:
  76.     pass
  77. encode_basestring_ascii = py_encode_basestring_ascii
  78.  
  79. class JSONEncoder(object):
  80.     '''Extensible JSON <http://json.org> encoder for Python data structures.
  81.  
  82.     Supports the following objects and types by default:
  83.  
  84.     +-------------------+---------------+
  85.     | Python            | JSON          |
  86.     +===================+===============+
  87.     | dict              | object        |
  88.     +-------------------+---------------+
  89.     | list, tuple       | array         |
  90.     +-------------------+---------------+
  91.     | str, unicode      | string        |
  92.     +-------------------+---------------+
  93.     | int, long, float  | number        |
  94.     +-------------------+---------------+
  95.     | True              | true          |
  96.     +-------------------+---------------+
  97.     | False             | false         |
  98.     +-------------------+---------------+
  99.     | None              | null          |
  100.     +-------------------+---------------+
  101.  
  102.     To extend this to recognize other objects, subclass and implement a
  103.     ``.default()`` method with another method that returns a serializable
  104.     object for ``o`` if possible, otherwise it should call the superclass
  105.     implementation (to raise ``TypeError``).
  106.  
  107.     '''
  108.     item_separator = ', '
  109.     key_separator = ': '
  110.     
  111.     def __init__(self, skipkeys = False, ensure_ascii = True, check_circular = True, allow_nan = True, sort_keys = False, indent = None, separators = None, encoding = 'utf-8', default = None):
  112.         """Constructor for JSONEncoder, with sensible defaults.
  113.  
  114.         If skipkeys is false, then it is a TypeError to attempt
  115.         encoding of keys that are not str, int, long, float or None.  If
  116.         skipkeys is True, such items are simply skipped.
  117.  
  118.         If ensure_ascii is true, the output is guaranteed to be str
  119.         objects with all incoming unicode characters escaped.  If
  120.         ensure_ascii is false, the output will be unicode object.
  121.  
  122.         If check_circular is true, then lists, dicts, and custom encoded
  123.         objects will be checked for circular references during encoding to
  124.         prevent an infinite recursion (which would cause an OverflowError).
  125.         Otherwise, no such check takes place.
  126.  
  127.         If allow_nan is true, then NaN, Infinity, and -Infinity will be
  128.         encoded as such.  This behavior is not JSON specification compliant,
  129.         but is consistent with most JavaScript based encoders and decoders.
  130.         Otherwise, it will be a ValueError to encode such floats.
  131.  
  132.         If sort_keys is true, then the output of dictionaries will be
  133.         sorted by key; this is useful for regression tests to ensure
  134.         that JSON serializations can be compared on a day-to-day basis.
  135.  
  136.         If indent is a non-negative integer, then JSON array
  137.         elements and object members will be pretty-printed with that
  138.         indent level.  An indent level of 0 will only insert newlines.
  139.         None is the most compact representation.
  140.  
  141.         If specified, separators should be a (item_separator, key_separator)
  142.         tuple.  The default is (', ', ': ').  To get the most compact JSON
  143.         representation you should specify (',', ':') to eliminate whitespace.
  144.  
  145.         If specified, default is a function that gets called for objects
  146.         that can't otherwise be serialized.  It should return a JSON encodable
  147.         version of the object or raise a ``TypeError``.
  148.  
  149.         If encoding is not None, then all input strings will be
  150.         transformed into unicode using that encoding prior to JSON-encoding.
  151.         The default is UTF-8.
  152.  
  153.         """
  154.         self.skipkeys = skipkeys
  155.         self.ensure_ascii = ensure_ascii
  156.         self.check_circular = check_circular
  157.         self.allow_nan = allow_nan
  158.         self.sort_keys = sort_keys
  159.         self.indent = indent
  160.         if separators is not None:
  161.             (self.item_separator, self.key_separator) = separators
  162.         
  163.         if default is not None:
  164.             self.default = default
  165.         
  166.         self.encoding = encoding
  167.  
  168.     
  169.     def default(self, o):
  170.         '''Implement this method in a subclass such that it returns
  171.         a serializable object for ``o``, or calls the base implementation
  172.         (to raise a ``TypeError``).
  173.  
  174.         For example, to support arbitrary iterators, you could
  175.         implement default like this::
  176.  
  177.             def default(self, o):
  178.                 try:
  179.                     iterable = iter(o)
  180.                 except TypeError:
  181.                     pass
  182.                 else:
  183.                     return list(iterable)
  184.                 return JSONEncoder.default(self, o)
  185.  
  186.         '''
  187.         raise TypeError(repr(o) + ' is not JSON serializable')
  188.  
  189.     
  190.     def encode(self, o):
  191.         '''Return a JSON string representation of a Python data structure.
  192.  
  193.         >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
  194.         \'{"foo": ["bar", "baz"]}\'
  195.  
  196.         '''
  197.         if isinstance(o, basestring):
  198.             if isinstance(o, str):
  199.                 _encoding = self.encoding
  200.                 if _encoding is not None and not (_encoding == 'utf-8'):
  201.                     o = o.decode(_encoding)
  202.                 
  203.             
  204.             if self.ensure_ascii:
  205.                 return encode_basestring_ascii(o)
  206.             else:
  207.                 return encode_basestring(o)
  208.         
  209.         chunks = self.iterencode(o, _one_shot = True)
  210.         if not isinstance(chunks, (list, tuple)):
  211.             chunks = list(chunks)
  212.         
  213.         return ''.join(chunks)
  214.  
  215.     
  216.     def iterencode(self, o, _one_shot = False):
  217.         '''Encode the given object and yield each string
  218.         representation as available.
  219.  
  220.         For example::
  221.  
  222.             for chunk in JSONEncoder().iterencode(bigobject):
  223.                 mysocket.write(chunk)
  224.  
  225.         '''
  226.         if self.check_circular:
  227.             markers = { }
  228.         else:
  229.             markers = None
  230.         if self.ensure_ascii:
  231.             _encoder = encode_basestring_ascii
  232.         else:
  233.             _encoder = encode_basestring
  234.         if self.encoding != 'utf-8':
  235.             
  236.             def _encoder(o, _orig_encoder = _encoder, _encoding = self.encoding):
  237.                 if isinstance(o, str):
  238.                     o = o.decode(_encoding)
  239.                 
  240.                 return _orig_encoder(o)
  241.  
  242.         
  243.         
  244.         def floatstr(o, allow_nan = self.allow_nan, _repr = FLOAT_REPR, _inf = INFINITY, _neginf = -INFINITY):
  245.             if o != o:
  246.                 text = 'NaN'
  247.             elif o == _inf:
  248.                 text = 'Infinity'
  249.             elif o == _neginf:
  250.                 text = '-Infinity'
  251.             else:
  252.                 return _repr(o)
  253.             if not allow_nan:
  254.                 raise ValueError('Out of range float values are not JSON compliant: ' + repr(o))
  255.             
  256.             return text
  257.  
  258.         if _one_shot and c_make_encoder is not None and not (self.indent) and not (self.sort_keys):
  259.             _iterencode = c_make_encoder(markers, self.default, _encoder, self.indent, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, self.allow_nan)
  260.         else:
  261.             _iterencode = _make_iterencode(markers, self.default, _encoder, self.indent, floatstr, self.key_separator, self.item_separator, self.sort_keys, self.skipkeys, _one_shot)
  262.         return _iterencode(o, 0)
  263.  
  264.  
  265.  
  266. def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, False = False, True = True, ValueError = ValueError, basestring = basestring, dict = dict, float = float, id = id, int = int, isinstance = isinstance, list = list, long = long, str = str, tuple = tuple):
  267.     
  268.     def _iterencode_list(lst, _current_indent_level):
  269.         if not lst:
  270.             yield '[]'
  271.             return None
  272.         
  273.         if markers is not None:
  274.             markerid = id(lst)
  275.             if markerid in markers:
  276.                 raise ValueError('Circular reference detected')
  277.             
  278.             markers[markerid] = lst
  279.         
  280.         buf = '['
  281.         if _indent is not None:
  282.             _current_indent_level += 1
  283.             newline_indent = '\n' + ' ' * _indent * _current_indent_level
  284.             separator = _item_separator + newline_indent
  285.             buf += newline_indent
  286.         else:
  287.             newline_indent = None
  288.             separator = _item_separator
  289.         first = True
  290.         for value in lst:
  291.             if first:
  292.                 first = False
  293.             else:
  294.                 buf = separator
  295.             if isinstance(value, basestring):
  296.                 yield buf + _encoder(value)
  297.                 continue
  298.             if value is None:
  299.                 yield buf + 'null'
  300.                 continue
  301.             if value is True:
  302.                 yield buf + 'true'
  303.                 continue
  304.             if value is False:
  305.                 yield buf + 'false'
  306.                 continue
  307.             if isinstance(value, (int, long)):
  308.                 yield buf + str(value)
  309.                 continue
  310.             if isinstance(value, float):
  311.                 yield buf + _floatstr(value)
  312.                 continue
  313.             yield buf
  314.             if isinstance(value, (list, tuple)):
  315.                 chunks = _iterencode_list(value, _current_indent_level)
  316.             elif isinstance(value, dict):
  317.                 chunks = _iterencode_dict(value, _current_indent_level)
  318.             else:
  319.                 chunks = _iterencode(value, _current_indent_level)
  320.             for chunk in chunks:
  321.                 yield chunk
  322.             
  323.         
  324.         if newline_indent is not None:
  325.             _current_indent_level -= 1
  326.             yield '\n' + ' ' * _indent * _current_indent_level
  327.         
  328.         yield ']'
  329.         if markers is not None:
  330.             del markers[markerid]
  331.         
  332.  
  333.     
  334.     def _iterencode_dict(dct, _current_indent_level):
  335.         if not dct:
  336.             yield '{}'
  337.             return None
  338.         
  339.         if markers is not None:
  340.             markerid = id(dct)
  341.             if markerid in markers:
  342.                 raise ValueError('Circular reference detected')
  343.             
  344.             markers[markerid] = dct
  345.         
  346.         yield '{'
  347.         if _indent is not None:
  348.             _current_indent_level += 1
  349.             newline_indent = '\n' + ' ' * _indent * _current_indent_level
  350.             item_separator = _item_separator + newline_indent
  351.             yield newline_indent
  352.         else:
  353.             newline_indent = None
  354.             item_separator = _item_separator
  355.         first = True
  356.         if _sort_keys:
  357.             items = dct.items()
  358.             items.sort(key = (lambda kv: kv[0]))
  359.         else:
  360.             items = dct.iteritems()
  361.         for key, value in items:
  362.             if isinstance(key, basestring):
  363.                 pass
  364.             elif isinstance(key, float):
  365.                 key = _floatstr(key)
  366.             elif key is True:
  367.                 key = 'true'
  368.             elif key is False:
  369.                 key = 'false'
  370.             elif key is None:
  371.                 key = 'null'
  372.             elif isinstance(key, (int, long)):
  373.                 key = str(key)
  374.             elif _skipkeys:
  375.                 continue
  376.             else:
  377.                 raise TypeError('key ' + repr(key) + ' is not a string')
  378.             if first:
  379.                 first = False
  380.             else:
  381.                 yield item_separator
  382.             yield _encoder(key)
  383.             yield _key_separator
  384.             if isinstance(value, basestring):
  385.                 yield _encoder(value)
  386.                 continue
  387.             if value is None:
  388.                 yield 'null'
  389.                 continue
  390.             if value is True:
  391.                 yield 'true'
  392.                 continue
  393.             if value is False:
  394.                 yield 'false'
  395.                 continue
  396.             if isinstance(value, (int, long)):
  397.                 yield str(value)
  398.                 continue
  399.             if isinstance(value, float):
  400.                 yield _floatstr(value)
  401.                 continue
  402.             if isinstance(value, (list, tuple)):
  403.                 chunks = _iterencode_list(value, _current_indent_level)
  404.             elif isinstance(value, dict):
  405.                 chunks = _iterencode_dict(value, _current_indent_level)
  406.             else:
  407.                 chunks = _iterencode(value, _current_indent_level)
  408.             for chunk in chunks:
  409.                 yield chunk
  410.             
  411.         
  412.         if newline_indent is not None:
  413.             _current_indent_level -= 1
  414.             yield '\n' + ' ' * _indent * _current_indent_level
  415.         
  416.         yield '}'
  417.         if markers is not None:
  418.             del markers[markerid]
  419.         
  420.  
  421.     
  422.     def _iterencode(o, _current_indent_level):
  423.         if isinstance(o, basestring):
  424.             yield _encoder(o)
  425.         elif o is None:
  426.             yield 'null'
  427.         elif o is True:
  428.             yield 'true'
  429.         elif o is False:
  430.             yield 'false'
  431.         elif isinstance(o, (int, long)):
  432.             yield str(o)
  433.         elif isinstance(o, float):
  434.             yield _floatstr(o)
  435.         elif isinstance(o, (list, tuple)):
  436.             for chunk in _iterencode_list(o, _current_indent_level):
  437.                 yield chunk
  438.             
  439.         elif isinstance(o, dict):
  440.             for chunk in _iterencode_dict(o, _current_indent_level):
  441.                 yield chunk
  442.             
  443.         elif markers is not None:
  444.             markerid = id(o)
  445.             if markerid in markers:
  446.                 raise ValueError('Circular reference detected')
  447.             
  448.             markers[markerid] = o
  449.         
  450.         o = _default(o)
  451.         for chunk in _iterencode(o, _current_indent_level):
  452.             yield chunk
  453.         
  454.         if markers is not None:
  455.             del markers[markerid]
  456.         
  457.  
  458.     return _iterencode
  459.  
  460.