app/django/utils/simplejson/__init__.py
changeset 323 ff1a9aa48cfd
parent 54 03e267d67478
equal deleted inserted replaced
322:6641e941ef1e 323:ff1a9aa48cfd
    63     ...     return dct
    63     ...     return dct
    64     ... 
    64     ... 
    65     >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
    65     >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
    66     ...     object_hook=as_complex)
    66     ...     object_hook=as_complex)
    67     (1+2j)
    67     (1+2j)
       
    68     >>> import decimal
       
    69     >>> simplejson.loads('1.1', parse_float=decimal.Decimal)
       
    70     Decimal("1.1")
    68 
    71 
    69 Extending JSONEncoder::
    72 Extending JSONEncoder::
    70     
    73     
    71     >>> import simplejson
    74     >>> import simplejson
    72     >>> class ComplexEncoder(simplejson.JSONEncoder):
    75     >>> class ComplexEncoder(simplejson.JSONEncoder):
    81     '[2.0, 1.0]'
    84     '[2.0, 1.0]'
    82     >>> list(ComplexEncoder().iterencode(2 + 1j))
    85     >>> list(ComplexEncoder().iterencode(2 + 1j))
    83     ['[', '2.0', ', ', '1.0', ']']
    86     ['[', '2.0', ', ', '1.0', ']']
    84     
    87     
    85 
    88 
       
    89 Using simplejson from the shell to validate and
       
    90 pretty-print::
       
    91     
       
    92     $ echo '{"json":"obj"}' | python -msimplejson.tool
       
    93     {
       
    94         "json": "obj"
       
    95     }
       
    96     $ echo '{ 1.2:3.4}' | python -msimplejson.tool
       
    97     Expecting property name: line 1 column 2 (char 2)
       
    98 
    86 Note that the JSON produced by this module's default settings
    99 Note that the JSON produced by this module's default settings
    87 is a subset of YAML, so it may be used as a serializer for that as well.
   100 is a subset of YAML, so it may be used as a serializer for that as well.
    88 """
   101 """
    89 __version__ = '1.5'
   102 __version__ = '1.9.2'
    90 __all__ = [
   103 __all__ = [
    91     'dump', 'dumps', 'load', 'loads',
   104     'dump', 'dumps', 'load', 'loads',
    92     'JSONDecoder', 'JSONEncoder',
   105     'JSONDecoder', 'JSONEncoder',
    93 ]
   106 ]
    94 
   107 
    95 from django.utils.simplejson.decoder import JSONDecoder
   108 if __name__ == '__main__':
    96 from django.utils.simplejson.encoder import JSONEncoder
   109     import warnings
       
   110     warnings.warn('python -msimplejson is deprecated, use python -msiplejson.tool', DeprecationWarning)
       
   111     from django.utils.simplejson.decoder import JSONDecoder
       
   112     from django.utils.simplejson.encoder import JSONEncoder
       
   113 else:
       
   114     from decoder import JSONDecoder
       
   115     from encoder import JSONEncoder
       
   116 
       
   117 _default_encoder = JSONEncoder(
       
   118     skipkeys=False,
       
   119     ensure_ascii=True,
       
   120     check_circular=True,
       
   121     allow_nan=True,
       
   122     indent=None,
       
   123     separators=None,
       
   124     encoding='utf-8',
       
   125     default=None,
       
   126 )
    97 
   127 
    98 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
   128 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
    99         allow_nan=True, cls=None, indent=None, **kw):
   129         allow_nan=True, cls=None, indent=None, separators=None,
       
   130         encoding='utf-8', default=None, **kw):
   100     """
   131     """
   101     Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
   132     Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
   102     ``.write()``-supporting file-like object).
   133     ``.write()``-supporting file-like object).
   103 
   134 
   104     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   135     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   105     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   136     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   106     will be skipped instead of raising a ``TypeError``.
   137     will be skipped instead of raising a ``TypeError``.
   107 
   138 
   108     If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
   139     If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
   109     may be ``unicode`` instances, subject to normal Python ``str`` to
   140     may be ``unicode`` instances, subject to normal Python ``str`` to
   110     ``unicode`` coercion rules.  Unless ``fp.write()`` explicitly
   141     ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
   111     understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
   142     understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
   112     to cause an error.
   143     to cause an error.
   113 
   144 
   114     If ``check_circular`` is ``False``, then the circular reference check
   145     If ``check_circular`` is ``False``, then the circular reference check
   115     for container types will be skipped and a circular reference will
   146     for container types will be skipped and a circular reference will
   119     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
   150     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
   120     in strict compliance of the JSON specification, instead of using the
   151     in strict compliance of the JSON specification, instead of using the
   121     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   152     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   122 
   153 
   123     If ``indent`` is a non-negative integer, then JSON array elements and object
   154     If ``indent`` is a non-negative integer, then JSON array elements and object
   124     members will be pretty-printed with that indent level.  An indent level
   155     members will be pretty-printed with that indent level. An indent level
   125     of 0 will only insert newlines.  ``None`` is the most compact representation.
   156     of 0 will only insert newlines. ``None`` is the most compact representation.
       
   157 
       
   158     If ``separators`` is an ``(item_separator, dict_separator)`` tuple
       
   159     then it will be used instead of the default ``(', ', ': ')`` separators.
       
   160     ``(',', ':')`` is the most compact JSON representation.
       
   161 
       
   162     ``encoding`` is the character encoding for str instances, default is UTF-8.
       
   163 
       
   164     ``default(obj)`` is a function that should return a serializable version
       
   165     of obj or raise TypeError. The default simply raises TypeError.
   126 
   166 
   127     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   167     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   128     ``.default()`` method to serialize additional types), specify it with
   168     ``.default()`` method to serialize additional types), specify it with
   129     the ``cls`` kwarg.
   169     the ``cls`` kwarg.
   130     """
   170     """
   131     if cls is None:
   171     # cached encoder
   132         cls = JSONEncoder
   172     if (skipkeys is False and ensure_ascii is True and
   133     iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   173         check_circular is True and allow_nan is True and
   134         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   174         cls is None and indent is None and separators is None and
   135         **kw).iterencode(obj)
   175         encoding == 'utf-8' and default is None and not kw):
       
   176         iterable = _default_encoder.iterencode(obj)
       
   177     else:
       
   178         if cls is None:
       
   179             cls = JSONEncoder
       
   180         iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
       
   181             check_circular=check_circular, allow_nan=allow_nan, indent=indent,
       
   182             separators=separators, encoding=encoding,
       
   183             default=default, **kw).iterencode(obj)
   136     # could accelerate with writelines in some versions of Python, at
   184     # could accelerate with writelines in some versions of Python, at
   137     # a debuggability cost
   185     # a debuggability cost
   138     for chunk in iterable:
   186     for chunk in iterable:
   139         fp.write(chunk)
   187         fp.write(chunk)
   140 
   188 
       
   189 
   141 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
   190 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
   142         allow_nan=True, cls=None, indent=None, separators=None, **kw):
   191         allow_nan=True, cls=None, indent=None, separators=None,
       
   192         encoding='utf-8', default=None, **kw):
   143     """
   193     """
   144     Serialize ``obj`` to a JSON formatted ``str``.
   194     Serialize ``obj`` to a JSON formatted ``str``.
   145 
   195 
   146     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   196     If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   147     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   197     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   159     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
   209     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
   160     strict compliance of the JSON specification, instead of using the
   210     strict compliance of the JSON specification, instead of using the
   161     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   211     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   162 
   212 
   163     If ``indent`` is a non-negative integer, then JSON array elements and
   213     If ``indent`` is a non-negative integer, then JSON array elements and
   164     object members will be pretty-printed with that indent level.  An indent
   214     object members will be pretty-printed with that indent level. An indent
   165     level of 0 will only insert newlines.  ``None`` is the most compact
   215     level of 0 will only insert newlines. ``None`` is the most compact
   166     representation.
   216     representation.
   167 
   217 
   168     If ``separators`` is an ``(item_separator, dict_separator)`` tuple
   218     If ``separators`` is an ``(item_separator, dict_separator)`` tuple
   169     then it will be used instead of the default ``(', ', ': ')`` separators.
   219     then it will be used instead of the default ``(', ', ': ')`` separators.
   170     ``(',', ':')`` is the most compact JSON representation.
   220     ``(',', ':')`` is the most compact JSON representation.
   171 
   221 
       
   222     ``encoding`` is the character encoding for str instances, default is UTF-8.
       
   223 
       
   224     ``default(obj)`` is a function that should return a serializable version
       
   225     of obj or raise TypeError. The default simply raises TypeError.
       
   226 
   172     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   227     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   173     ``.default()`` method to serialize additional types), specify it with
   228     ``.default()`` method to serialize additional types), specify it with
   174     the ``cls`` kwarg.
   229     the ``cls`` kwarg.
   175     """
   230     """
       
   231     # cached encoder
       
   232     if (skipkeys is False and ensure_ascii is True and
       
   233         check_circular is True and allow_nan is True and
       
   234         cls is None and indent is None and separators is None and
       
   235         encoding == 'utf-8' and default is None and not kw):
       
   236         return _default_encoder.encode(obj)
   176     if cls is None:
   237     if cls is None:
   177         cls = JSONEncoder
   238         cls = JSONEncoder
   178     return cls(
   239     return cls(
   179         skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   240         skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   180         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   241         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   181         separators=separators,
   242         separators=separators, encoding=encoding, default=default,
   182         **kw).encode(obj)
   243         **kw).encode(obj)
   183 
   244 
   184 def load(fp, encoding=None, cls=None, object_hook=None, **kw):
   245 
       
   246 _default_decoder = JSONDecoder(encoding=None, object_hook=None)
       
   247 
       
   248 
       
   249 def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
       
   250         parse_int=None, parse_constant=None, **kw):
   185     """
   251     """
   186     Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
   252     Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
   187     a JSON document) to a Python object.
   253     a JSON document) to a Python object.
   188 
   254 
   189     If the contents of ``fp`` is encoded with an ASCII based encoding other
   255     If the contents of ``fp`` is encoded with an ASCII based encoding other
   190     than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
   256     than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
   191     be specified.  Encodings that are not ASCII based (such as UCS-2) are
   257     be specified. Encodings that are not ASCII based (such as UCS-2) are
   192     not allowed, and should be wrapped with
   258     not allowed, and should be wrapped with
   193     ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
   259     ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
   194     object and passed to ``loads()``
   260     object and passed to ``loads()``
   195 
   261 
   196     ``object_hook`` is an optional function that will be called with the
   262     ``object_hook`` is an optional function that will be called with the
   197     result of any object literal decode (a ``dict``).  The return value of
   263     result of any object literal decode (a ``dict``). The return value of
   198     ``object_hook`` will be used instead of the ``dict``.  This feature
   264     ``object_hook`` will be used instead of the ``dict``. This feature
   199     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
   265     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
   200     
   266     
   201     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
   267     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
   202     kwarg.
   268     kwarg.
   203     """
   269     """
       
   270     return loads(fp.read(),
       
   271         encoding=encoding, cls=cls, object_hook=object_hook,
       
   272         parse_float=parse_float, parse_int=parse_int,
       
   273         parse_constant=parse_constant, **kw)
       
   274 
       
   275 
       
   276 def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
       
   277         parse_int=None, parse_constant=None, **kw):
       
   278     """
       
   279     Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
       
   280     document) to a Python object.
       
   281 
       
   282     If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
       
   283     other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
       
   284     must be specified. Encodings that are not ASCII based (such as UCS-2)
       
   285     are not allowed and should be decoded to ``unicode`` first.
       
   286 
       
   287     ``object_hook`` is an optional function that will be called with the
       
   288     result of any object literal decode (a ``dict``). The return value of
       
   289     ``object_hook`` will be used instead of the ``dict``. This feature
       
   290     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
       
   291 
       
   292     ``parse_float``, if specified, will be called with the string
       
   293     of every JSON float to be decoded. By default this is equivalent to
       
   294     float(num_str). This can be used to use another datatype or parser
       
   295     for JSON floats (e.g. decimal.Decimal).
       
   296 
       
   297     ``parse_int``, if specified, will be called with the string
       
   298     of every JSON int to be decoded. By default this is equivalent to
       
   299     int(num_str). This can be used to use another datatype or parser
       
   300     for JSON integers (e.g. float).
       
   301 
       
   302     ``parse_constant``, if specified, will be called with one of the
       
   303     following strings: -Infinity, Infinity, NaN, null, true, false.
       
   304     This can be used to raise an exception if invalid JSON numbers
       
   305     are encountered.
       
   306 
       
   307     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
       
   308     kwarg.
       
   309     """
       
   310     if (cls is None and encoding is None and object_hook is None and
       
   311             parse_int is None and parse_float is None and
       
   312             parse_constant is None and not kw):
       
   313         return _default_decoder.decode(s)
   204     if cls is None:
   314     if cls is None:
   205         cls = JSONDecoder
   315         cls = JSONDecoder
   206     if object_hook is not None:
   316     if object_hook is not None:
   207         kw['object_hook'] = object_hook
   317         kw['object_hook'] = object_hook
   208     return cls(encoding=encoding, **kw).decode(fp.read())
   318     if parse_float is not None:
   209 
   319         kw['parse_float'] = parse_float
   210 def loads(s, encoding=None, cls=None, object_hook=None, **kw):
   320     if parse_int is not None:
   211     """
   321         kw['parse_int'] = parse_int
   212     Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
   322     if parse_constant is not None:
   213     document) to a Python object.
   323         kw['parse_constant'] = parse_constant
   214 
       
   215     If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
       
   216     other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
       
   217     must be specified.  Encodings that are not ASCII based (such as UCS-2)
       
   218     are not allowed and should be decoded to ``unicode`` first.
       
   219 
       
   220     ``object_hook`` is an optional function that will be called with the
       
   221     result of any object literal decode (a ``dict``).  The return value of
       
   222     ``object_hook`` will be used instead of the ``dict``.  This feature
       
   223     can be used to implement custom decoders (e.g. JSON-RPC class hinting).
       
   224 
       
   225     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
       
   226     kwarg.
       
   227     """
       
   228     if cls is None:
       
   229         cls = JSONDecoder
       
   230     if object_hook is not None:
       
   231         kw['object_hook'] = object_hook
       
   232     return cls(encoding=encoding, **kw).decode(s)
   324     return cls(encoding=encoding, **kw).decode(s)
   233 
   325 
       
   326 
       
   327 #
       
   328 # Compatibility cruft from other libraries
       
   329 #
       
   330 
       
   331 
       
   332 def decode(s):
       
   333     """
       
   334     demjson, python-cjson API compatibility hook. Use loads(s) instead.
       
   335     """
       
   336     import warnings
       
   337     warnings.warn("simplejson.loads(s) should be used instead of decode(s)",
       
   338         DeprecationWarning)
       
   339     return loads(s)
       
   340 
       
   341 
       
   342 def encode(obj):
       
   343     """
       
   344     demjson, python-cjson compatibility hook. Use dumps(s) instead.
       
   345     """
       
   346     import warnings
       
   347     warnings.warn("simplejson.dumps(s) should be used instead of encode(s)",
       
   348         DeprecationWarning)
       
   349     return dumps(obj)
       
   350 
       
   351 
   234 def read(s):
   352 def read(s):
   235     """
   353     """
   236     json-py API compatibility hook.  Use loads(s) instead.
   354     jsonlib, JsonUtils, python-json, json-py API compatibility hook.
       
   355     Use loads(s) instead.
   237     """
   356     """
   238     import warnings
   357     import warnings
   239     warnings.warn("simplejson.loads(s) should be used instead of read(s)",
   358     warnings.warn("simplejson.loads(s) should be used instead of read(s)",
   240         DeprecationWarning)
   359         DeprecationWarning)
   241     return loads(s)
   360     return loads(s)
   242 
   361 
       
   362 
   243 def write(obj):
   363 def write(obj):
   244     """
   364     """
   245     json-py API compatibility hook.  Use dumps(s) instead.
   365     jsonlib, JsonUtils, python-json, json-py API compatibility hook.
       
   366     Use dumps(s) instead.
   246     """
   367     """
   247     import warnings
   368     import warnings
   248     warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
   369     warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
   249         DeprecationWarning)
   370         DeprecationWarning)
   250     return dumps(obj)
   371     return dumps(obj)
   251 
   372 
   252 
   373 
       
   374 if __name__ == '__main__':
       
   375     import simplejson.tool
       
   376     simplejson.tool.main()