Code

Ticket #18023: remove_simplejson.diff

File remove_simplejson.diff, 48.3 KB (added by ogier, 2 years ago)
Line 
1diff --git a/django/utils/simplejson/LICENSE.txt b/django/utils/simplejson/LICENSE.txt
2deleted file mode 100644
3index ad95f29..0000000
4--- a/django/utils/simplejson/LICENSE.txt
5+++ /dev/null
6@@ -1,19 +0,0 @@
7-Copyright (c) 2006 Bob Ippolito
8-
9-Permission is hereby granted, free of charge, to any person obtaining a copy of
10-this software and associated documentation files (the "Software"), to deal in
11-the Software without restriction, including without limitation the rights to
12-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13-of the Software, and to permit persons to whom the Software is furnished to do
14-so, subject to the following conditions:
15-
16-The above copyright notice and this permission notice shall be included in all
17-copies or substantial portions of the Software.
18-
19-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25-SOFTWARE.
26diff --git a/django/utils/simplejson/__init__.py b/django/utils/simplejson/__init__.py
27index a9418da..ea45572 100644
28--- a/django/utils/simplejson/__init__.py
29+++ b/django/utils/simplejson/__init__.py
30@@ -1,353 +1,27 @@
31-r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
32-JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
33-interchange format.
34+import warnings
35 
36-:mod:`simplejson` exposes an API familiar to users of the standard library
37-:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
38-version of the :mod:`json` library contained in Python 2.6, but maintains
39-compatibility with Python 2.4 and Python 2.5 and (currently) has
40-significant performance advantages, even without using the optional C
41-extension for speedups.
42+warnings.warn(
43+    "The 'django.utils.simplejson' module is deprecated, "
44+    "use 'json' from the standard library instead; "
45+    "please see the Django 1.5 release notes "
46+    "(https://docs.djangoproject.com/en/dev/releases/1.5/).",
47+    PendingDeprecationWarning)
48 
49-Encoding basic Python object hierarchies::
50-
51-    >>> import simplejson as json
52-    >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
53-    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
54-    >>> print json.dumps("\"foo\bar")
55-    "\"foo\bar"
56-    >>> print json.dumps(u'\u1234')
57-    "\u1234"
58-    >>> print json.dumps('\\')
59-    "\\"
60-    >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
61-    {"a": 0, "b": 0, "c": 0}
62-    >>> from StringIO import StringIO
63-    >>> io = StringIO()
64-    >>> json.dump(['streaming API'], io)
65-    >>> io.getvalue()
66-    '["streaming API"]'
67-
68-Compact encoding::
69-
70-    >>> import simplejson as json
71-    >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
72-    '[1,2,3,{"4":5,"6":7}]'
73-
74-Pretty printing::
75-
76-    >>> import simplejson as json
77-    >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
78-    >>> print '\n'.join([l.rstrip() for l in  s.splitlines()])
79-    {
80-        "4": 5,
81-        "6": 7
82-    }
83-
84-Decoding JSON::
85-
86-    >>> import simplejson as json
87-    >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
88-    >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
89-    True
90-    >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
91-    True
92-    >>> from StringIO import StringIO
93-    >>> io = StringIO('["streaming API"]')
94-    >>> json.load(io)[0] == 'streaming API'
95-    True
96-
97-Specializing JSON object decoding::
98-
99-    >>> import simplejson as json
100-    >>> def as_complex(dct):
101-    ...     if '__complex__' in dct:
102-    ...         return complex(dct['real'], dct['imag'])
103-    ...     return dct
104-    ...
105-    >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
106-    ...     object_hook=as_complex)
107-    (1+2j)
108-    >>> import decimal
109-    >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
110-    True
111-
112-Specializing JSON object encoding::
113-
114-    >>> import simplejson as json
115-    >>> def encode_complex(obj):
116-    ...     if isinstance(obj, complex):
117-    ...         return [obj.real, obj.imag]
118-    ...     raise TypeError("%r is not JSON serializable" % (o,))
119-    ...
120-    >>> json.dumps(2 + 1j, default=encode_complex)
121-    '[2.0, 1.0]'
122-    >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
123-    '[2.0, 1.0]'
124-    >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
125-    '[2.0, 1.0]'
126-
127-
128-Using simplejson.tool from the shell to validate and pretty-print::
129-
130-    $ echo '{"json":"obj"}' | python -msimplejson.tool
131-    {
132-        "json": "obj"
133-    }
134-    $ echo '{ 1.2:3.4}' | python -msimplejson.tool
135-    Expecting property name: line 1 column 2 (char 2)
136-"""
137-
138-# Django modification: try to use the system version first, providing it's
139-# either of a later version of has the C speedups in place. Otherwise, fall
140-# back to our local copy.
141-
142-__version__ = '2.0.7'
143-
144-use_system_version = False
145+# Try to use the system simplejson first. If that fails, use python's standard
146+# json module.
147 try:
148-    # The system-installed version has priority providing it is either not an
149-    # earlier version or it contains the C speedups.
150-    import simplejson
151-    if (simplejson.__version__.split('.') >= __version__.split('.') or
152-            hasattr(simplejson, '_speedups')):
153-        from simplejson import *
154-        use_system_version = True
155-        # Make sure we copy over the version. See #17071
156-        __version__ = simplejson.__version__
157+    # This file must reside at simplejson/__init__.py or else these lines
158+    # can cause a circular self-import.
159+    from simplejson import *
160+    from simplejson import __version__
161 except ImportError:
162-    pass
163+    from json import *
164+    from json import __version__
165 
166-if not use_system_version:
167     try:
168-        from json import *      # Python 2.6 preferred over local copy.
169-
170         # There is a "json" package around that is not Python's "json", so we
171         # check for something that is only in the namespace of the version we
172         # want.
173         JSONDecoder
174-
175-        use_system_version = True
176-        # Make sure we copy over the version. See #17071
177-        __version__ = json.__version__
178-    except (ImportError, NameError):
179-        pass
180-
181-# If all else fails, we have a bundled version that can be used.
182-if not use_system_version:
183-    __all__ = [
184-        'dump', 'dumps', 'load', 'loads',
185-        'JSONDecoder', 'JSONEncoder',
186-    ]
187-
188-    from django.utils.simplejson.decoder import JSONDecoder
189-    from django.utils.simplejson.encoder import JSONEncoder
190-
191-    _default_encoder = JSONEncoder(
192-        skipkeys=False,
193-        ensure_ascii=True,
194-        check_circular=True,
195-        allow_nan=True,
196-        indent=None,
197-        separators=None,
198-        encoding='utf-8',
199-        default=None,
200-    )
201-
202-    def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
203-            allow_nan=True, cls=None, indent=None, separators=None,
204-            encoding='utf-8', default=None, **kw):
205-        """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
206-        ``.write()``-supporting file-like object).
207-
208-        If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
209-        (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
210-        will be skipped instead of raising a ``TypeError``.
211-
212-        If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
213-        may be ``unicode`` instances, subject to normal Python ``str`` to
214-        ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
215-        understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
216-        to cause an error.
217-
218-        If ``check_circular`` is ``False``, then the circular reference check
219-        for container types will be skipped and a circular reference will
220-        result in an ``OverflowError`` (or worse).
221-
222-        If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
223-        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
224-        in strict compliance of the JSON specification, instead of using the
225-        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
226-
227-        If ``indent`` is a non-negative integer, then JSON array elements and object
228-        members will be pretty-printed with that indent level. An indent level
229-        of 0 will only insert newlines. ``None`` is the most compact representation.
230-
231-        If ``separators`` is an ``(item_separator, dict_separator)`` tuple
232-        then it will be used instead of the default ``(', ', ': ')`` separators.
233-        ``(',', ':')`` is the most compact JSON representation.
234-
235-        ``encoding`` is the character encoding for str instances, default is UTF-8.
236-
237-        ``default(obj)`` is a function that should return a serializable version
238-        of obj or raise TypeError. The default simply raises TypeError.
239-
240-        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
241-        ``.default()`` method to serialize additional types), specify it with
242-        the ``cls`` kwarg.
243-
244-        """
245-        # cached encoder
246-        if (skipkeys is False and ensure_ascii is True and
247-            check_circular is True and allow_nan is True and
248-            cls is None and indent is None and separators is None and
249-            encoding == 'utf-8' and default is None and not kw):
250-            iterable = _default_encoder.iterencode(obj)
251-        else:
252-            if cls is None:
253-                cls = JSONEncoder
254-            iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
255-                check_circular=check_circular, allow_nan=allow_nan, indent=indent,
256-                separators=separators, encoding=encoding,
257-                default=default, **kw).iterencode(obj)
258-        # could accelerate with writelines in some versions of Python, at
259-        # a debuggability cost
260-        for chunk in iterable:
261-            fp.write(chunk)
262-
263-
264-    def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
265-            allow_nan=True, cls=None, indent=None, separators=None,
266-            encoding='utf-8', default=None, **kw):
267-        """Serialize ``obj`` to a JSON formatted ``str``.
268-
269-        If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
270-        (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
271-        will be skipped instead of raising a ``TypeError``.
272-
273-        If ``ensure_ascii`` is ``False``, then the return value will be a
274-        ``unicode`` instance subject to normal Python ``str`` to ``unicode``
275-        coercion rules instead of being escaped to an ASCII ``str``.
276-
277-        If ``check_circular`` is ``False``, then the circular reference check
278-        for container types will be skipped and a circular reference will
279-        result in an ``OverflowError`` (or worse).
280-
281-        If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
282-        serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
283-        strict compliance of the JSON specification, instead of using the
284-        JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
285-
286-        If ``indent`` is a non-negative integer, then JSON array elements and
287-        object members will be pretty-printed with that indent level. An indent
288-        level of 0 will only insert newlines. ``None`` is the most compact
289-        representation.
290-
291-        If ``separators`` is an ``(item_separator, dict_separator)`` tuple
292-        then it will be used instead of the default ``(', ', ': ')`` separators.
293-        ``(',', ':')`` is the most compact JSON representation.
294-
295-        ``encoding`` is the character encoding for str instances, default is UTF-8.
296-
297-        ``default(obj)`` is a function that should return a serializable version
298-        of obj or raise TypeError. The default simply raises TypeError.
299-
300-        To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
301-        ``.default()`` method to serialize additional types), specify it with
302-        the ``cls`` kwarg.
303-
304-        """
305-        # cached encoder
306-        if (skipkeys is False and ensure_ascii is True and
307-            check_circular is True and allow_nan is True and
308-            cls is None and indent is None and separators is None and
309-            encoding == 'utf-8' and default is None and not kw):
310-            return _default_encoder.encode(obj)
311-        if cls is None:
312-            cls = JSONEncoder
313-        return cls(
314-            skipkeys=skipkeys, ensure_ascii=ensure_ascii,
315-            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
316-            separators=separators, encoding=encoding, default=default,
317-            **kw).encode(obj)
318-
319-
320-    _default_decoder = JSONDecoder(encoding=None, object_hook=None)
321-
322-
323-    def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
324-            parse_int=None, parse_constant=None, **kw):
325-        """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
326-        a JSON document) to a Python object.
327-
328-        If the contents of ``fp`` is encoded with an ASCII based encoding other
329-        than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
330-        be specified. Encodings that are not ASCII based (such as UCS-2) are
331-        not allowed, and should be wrapped with
332-        ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
333-        object and passed to ``loads()``
334-
335-        ``object_hook`` is an optional function that will be called with the
336-        result of any object literal decode (a ``dict``). The return value of
337-        ``object_hook`` will be used instead of the ``dict``. This feature
338-        can be used to implement custom decoders (e.g. JSON-RPC class hinting).
339-
340-        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
341-        kwarg.
342-
343-        """
344-        return loads(fp.read(),
345-            encoding=encoding, cls=cls, object_hook=object_hook,
346-            parse_float=parse_float, parse_int=parse_int,
347-            parse_constant=parse_constant, **kw)
348-
349-
350-    def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
351-            parse_int=None, parse_constant=None, **kw):
352-        """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
353-        document) to a Python object.
354-
355-        If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
356-        other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
357-        must be specified. Encodings that are not ASCII based (such as UCS-2)
358-        are not allowed and should be decoded to ``unicode`` first.
359-
360-        ``object_hook`` is an optional function that will be called with the
361-        result of any object literal decode (a ``dict``). The return value of
362-        ``object_hook`` will be used instead of the ``dict``. This feature
363-        can be used to implement custom decoders (e.g. JSON-RPC class hinting).
364-
365-        ``parse_float``, if specified, will be called with the string
366-        of every JSON float to be decoded. By default this is equivalent to
367-        float(num_str). This can be used to use another datatype or parser
368-        for JSON floats (e.g. decimal.Decimal).
369-
370-        ``parse_int``, if specified, will be called with the string
371-        of every JSON int to be decoded. By default this is equivalent to
372-        int(num_str). This can be used to use another datatype or parser
373-        for JSON integers (e.g. float).
374-
375-        ``parse_constant``, if specified, will be called with one of the
376-        following strings: -Infinity, Infinity, NaN, null, true, false.
377-        This can be used to raise an exception if invalid JSON numbers
378-        are encountered.
379-
380-        To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
381-        kwarg.
382-
383-        """
384-        if (cls is None and encoding is None and object_hook is None and
385-                parse_int is None and parse_float is None and
386-                parse_constant is None and not kw):
387-            return _default_decoder.decode(s)
388-        if cls is None:
389-            cls = JSONDecoder
390-        if object_hook is not None:
391-            kw['object_hook'] = object_hook
392-        if parse_float is not None:
393-            kw['parse_float'] = parse_float
394-        if parse_int is not None:
395-            kw['parse_int'] = parse_int
396-        if parse_constant is not None:
397-            kw['parse_constant'] = parse_constant
398-        return cls(encoding=encoding, **kw).decode(s)
399+    except NameError:
400+        raise ImportError("Module 'json' is not from python's standard library")
401diff --git a/django/utils/simplejson/decoder.py b/django/utils/simplejson/decoder.py
402deleted file mode 100644
403index 5a845cc..0000000
404--- a/django/utils/simplejson/decoder.py
405+++ /dev/null
406@@ -1,345 +0,0 @@
407-"""Implementation of JSONDecoder
408-"""
409-import re
410-import sys
411-import struct
412-
413-from django.utils.simplejson.scanner import make_scanner
414-c_scanstring = None
415-
416-__all__ = ['JSONDecoder']
417-
418-FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
419-
420-def _floatconstants():
421-    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
422-    if sys.byteorder != 'big':
423-        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
424-    nan, inf = struct.unpack('dd', _BYTES)
425-    return nan, inf, -inf
426-
427-NaN, PosInf, NegInf = _floatconstants()
428-
429-
430-def linecol(doc, pos):
431-    lineno = doc.count('\n', 0, pos) + 1
432-    if lineno == 1:
433-        colno = pos
434-    else:
435-        colno = pos - doc.rindex('\n', 0, pos)
436-    return lineno, colno
437-
438-
439-def errmsg(msg, doc, pos, end=None):
440-    # Note that this function is called from _speedups
441-    lineno, colno = linecol(doc, pos)
442-    if end is None:
443-        return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
444-    endlineno, endcolno = linecol(doc, end)
445-    return '%s: line %d column %d - line %d column %d (char %d - %d)' % (
446-        msg, lineno, colno, endlineno, endcolno, pos, end)
447-
448-
449-_CONSTANTS = {
450-    '-Infinity': NegInf,
451-    'Infinity': PosInf,
452-    'NaN': NaN,
453-}
454-
455-STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
456-BACKSLASH = {
457-    '"': u'"', '\\': u'\\', '/': u'/',
458-    'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
459-}
460-
461-DEFAULT_ENCODING = "utf-8"
462-
463-def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
464-    """Scan the string s for a JSON string. End is the index of the
465-    character in s after the quote that started the JSON string.
466-    Unescapes all valid JSON string escape sequences and raises ValueError
467-    on attempt to decode an invalid string. If strict is False then literal
468-    control characters are allowed in the string.
469-   
470-    Returns a tuple of the decoded string and the index of the character in s
471-    after the end quote."""
472-    if encoding is None:
473-        encoding = DEFAULT_ENCODING
474-    chunks = []
475-    _append = chunks.append
476-    begin = end - 1
477-    while 1:
478-        chunk = _m(s, end)
479-        if chunk is None:
480-            raise ValueError(
481-                errmsg("Unterminated string starting at", s, begin))
482-        end = chunk.end()
483-        content, terminator = chunk.groups()
484-        # Content is contains zero or more unescaped string characters
485-        if content:
486-            if not isinstance(content, unicode):
487-                content = unicode(content, encoding)
488-            _append(content)
489-        # Terminator is the end of string, a literal control character,
490-        # or a backslash denoting that an escape sequence follows
491-        if terminator == '"':
492-            break
493-        elif terminator != '\\':
494-            if strict:
495-                msg = "Invalid control character %r at" % (terminator,)
496-                raise ValueError(msg, s, end)
497-            else:
498-                _append(terminator)
499-                continue
500-        try:
501-            esc = s[end]
502-        except IndexError:
503-            raise ValueError(
504-                errmsg("Unterminated string starting at", s, begin))
505-        # If not a unicode escape sequence, must be in the lookup table
506-        if esc != 'u':
507-            try:
508-                char = _b[esc]
509-            except KeyError:
510-                raise ValueError(
511-                    errmsg("Invalid \\escape: %r" % (esc,), s, end))
512-            end += 1
513-        else:
514-            # Unicode escape sequence
515-            esc = s[end + 1:end + 5]
516-            next_end = end + 5
517-            if len(esc) != 4:
518-                msg = "Invalid \\uXXXX escape"
519-                raise ValueError(errmsg(msg, s, end))
520-            uni = int(esc, 16)
521-            # Check for surrogate pair on UCS-4 systems
522-            if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
523-                msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
524-                if not s[end + 5:end + 7] == '\\u':
525-                    raise ValueError(errmsg(msg, s, end))
526-                esc2 = s[end + 7:end + 11]
527-                if len(esc2) != 4:
528-                    raise ValueError(errmsg(msg, s, end))
529-                uni2 = int(esc2, 16)
530-                uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
531-                next_end += 6
532-            char = unichr(uni)
533-            end = next_end
534-        # Append the unescaped character
535-        _append(char)
536-    return u''.join(chunks), end
537-
538-
539-# Use speedup if available
540-scanstring = c_scanstring or py_scanstring
541-
542-WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
543-WHITESPACE_STR = ' \t\n\r'
544-
545-def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
546-    pairs = {}
547-    # Use a slice to prevent IndexError from being raised, the following
548-    # check will raise a more specific ValueError if the string is empty
549-    nextchar = s[end:end + 1]
550-    # Normally we expect nextchar == '"'
551-    if nextchar != '"':
552-        if nextchar in _ws:
553-            end = _w(s, end).end()
554-            nextchar = s[end:end + 1]
555-        # Trivial empty object
556-        if nextchar == '}':
557-            return pairs, end + 1
558-        elif nextchar != '"':
559-            raise ValueError(errmsg("Expecting property name", s, end))
560-    end += 1
561-    while True:
562-        key, end = scanstring(s, end, encoding, strict)
563-
564-        # To skip some function call overhead we optimize the fast paths where
565-        # the JSON key separator is ": " or just ":".
566-        if s[end:end + 1] != ':':
567-            end = _w(s, end).end()
568-            if s[end:end + 1] != ':':
569-                raise ValueError(errmsg("Expecting : delimiter", s, end))
570-
571-        end += 1
572-
573-        try:
574-            if s[end] in _ws:
575-                end += 1
576-                if s[end] in _ws:
577-                    end = _w(s, end + 1).end()
578-        except IndexError:
579-            pass
580-
581-        try:
582-            value, end = scan_once(s, end)
583-        except StopIteration:
584-            raise ValueError(errmsg("Expecting object", s, end))
585-        pairs[key] = value
586-
587-        try:
588-            nextchar = s[end]
589-            if nextchar in _ws:
590-                end = _w(s, end + 1).end()
591-                nextchar = s[end]
592-        except IndexError:
593-            nextchar = ''
594-        end += 1
595-
596-        if nextchar == '}':
597-            break
598-        elif nextchar != ',':
599-            raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
600-
601-        try:
602-            nextchar = s[end]
603-            if nextchar in _ws:
604-                end += 1
605-                nextchar = s[end]
606-                if nextchar in _ws:
607-                    end = _w(s, end + 1).end()
608-                    nextchar = s[end]
609-        except IndexError:
610-            nextchar = ''
611-
612-        end += 1
613-        if nextchar != '"':
614-            raise ValueError(errmsg("Expecting property name", s, end - 1))
615-
616-    if object_hook is not None:
617-        pairs = object_hook(pairs)
618-    return pairs, end
619-
620-def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
621-    values = []
622-    nextchar = s[end:end + 1]
623-    if nextchar in _ws:
624-        end = _w(s, end + 1).end()
625-        nextchar = s[end:end + 1]
626-    # Look-ahead for trivial empty array
627-    if nextchar == ']':
628-        return values, end + 1
629-    _append = values.append
630-    while True:
631-        try:
632-            value, end = scan_once(s, end)
633-        except StopIteration:
634-            raise ValueError(errmsg("Expecting object", s, end))
635-        _append(value)
636-        nextchar = s[end:end + 1]
637-        if nextchar in _ws:
638-            end = _w(s, end + 1).end()
639-            nextchar = s[end:end + 1]
640-        end += 1
641-        if nextchar == ']':
642-            break
643-        elif nextchar != ',':
644-            raise ValueError(errmsg("Expecting , delimiter", s, end))
645-
646-        try:
647-            if s[end] in _ws:
648-                end += 1
649-                if s[end] in _ws:
650-                    end = _w(s, end + 1).end()
651-        except IndexError:
652-            pass
653-
654-    return values, end
655-
656-class JSONDecoder(object):
657-    """Simple JSON <http://json.org> decoder
658-
659-    Performs the following translations in decoding by default:
660-
661-    +---------------+-------------------+
662-    | JSON          | Python            |
663-    +===============+===================+
664-    | object        | dict              |
665-    +---------------+-------------------+
666-    | array         | list              |
667-    +---------------+-------------------+
668-    | string        | unicode           |
669-    +---------------+-------------------+
670-    | number (int)  | int, long         |
671-    +---------------+-------------------+
672-    | number (real) | float             |
673-    +---------------+-------------------+
674-    | true          | True              |
675-    +---------------+-------------------+
676-    | false         | False             |
677-    +---------------+-------------------+
678-    | null          | None              |
679-    +---------------+-------------------+
680-
681-    It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
682-    their corresponding ``float`` values, which is outside the JSON spec.
683-
684-    """
685-
686-    def __init__(self, encoding=None, object_hook=None, parse_float=None,
687-            parse_int=None, parse_constant=None, strict=True):
688-        """``encoding`` determines the encoding used to interpret any ``str``
689-        objects decoded by this instance (utf-8 by default).  It has no
690-        effect when decoding ``unicode`` objects.
691-
692-        Note that currently only encodings that are a superset of ASCII work,
693-        strings of other encodings should be passed in as ``unicode``.
694-
695-        ``object_hook``, if specified, will be called with the result
696-        of every JSON object decoded and its return value will be used in
697-        place of the given ``dict``.  This can be used to provide custom
698-        deserializations (e.g. to support JSON-RPC class hinting).
699-
700-        ``parse_float``, if specified, will be called with the string
701-        of every JSON float to be decoded. By default this is equivalent to
702-        float(num_str). This can be used to use another datatype or parser
703-        for JSON floats (e.g. decimal.Decimal).
704-
705-        ``parse_int``, if specified, will be called with the string
706-        of every JSON int to be decoded. By default this is equivalent to
707-        int(num_str). This can be used to use another datatype or parser
708-        for JSON integers (e.g. float).
709-
710-        ``parse_constant``, if specified, will be called with one of the
711-        following strings: -Infinity, Infinity, NaN.
712-        This can be used to raise an exception if invalid JSON numbers
713-        are encountered.
714-
715-        """
716-        self.encoding = encoding
717-        self.object_hook = object_hook
718-        self.parse_float = parse_float or float
719-        self.parse_int = parse_int or int
720-        self.parse_constant = parse_constant or _CONSTANTS.__getitem__
721-        self.strict = strict
722-        self.parse_object = JSONObject
723-        self.parse_array = JSONArray
724-        self.parse_string = scanstring
725-        self.scan_once = make_scanner(self)
726-
727-    def decode(self, s, _w=WHITESPACE.match):
728-        """Return the Python representation of ``s`` (a ``str`` or ``unicode``
729-        instance containing a JSON document)
730-
731-        """
732-        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
733-        end = _w(s, end).end()
734-        if end != len(s):
735-            raise ValueError(errmsg("Extra data", s, end, len(s)))
736-        return obj
737-
738-    def raw_decode(self, s, idx=0):
739-        """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
740-        with a JSON document) and return a 2-tuple of the Python
741-        representation and the index in ``s`` where the document ended.
742-
743-        This can be used to decode a JSON document from a string that may
744-        have extraneous data at the end.
745-
746-        """
747-        try:
748-            obj, end = self.scan_once(s, idx)
749-        except StopIteration:
750-            raise ValueError("No JSON object could be decoded")
751-        return obj, end
752diff --git a/django/utils/simplejson/encoder.py b/django/utils/simplejson/encoder.py
753deleted file mode 100644
754index 06ebe62..0000000
755--- a/django/utils/simplejson/encoder.py
756+++ /dev/null
757@@ -1,430 +0,0 @@
758-"""Implementation of JSONEncoder
759-"""
760-import re
761-
762-c_encode_basestring_ascii = None
763-c_make_encoder = None
764-
765-ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
766-ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
767-HAS_UTF8 = re.compile(r'[\x80-\xff]')
768-ESCAPE_DCT = {
769-    '\\': '\\\\',
770-    '"': '\\"',
771-    '\b': '\\b',
772-    '\f': '\\f',
773-    '\n': '\\n',
774-    '\r': '\\r',
775-    '\t': '\\t',
776-}
777-for i in range(0x20):
778-    ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
779-
780-# Assume this produces an infinity on all machines (probably not guaranteed)
781-INFINITY = float('1e66666')
782-FLOAT_REPR = repr
783-
784-def encode_basestring(s):
785-    """Return a JSON representation of a Python string
786-
787-    """
788-    def replace(match):
789-        return ESCAPE_DCT[match.group(0)]
790-    return '"' + ESCAPE.sub(replace, s) + '"'
791-
792-
793-def py_encode_basestring_ascii(s):
794-    """Return an ASCII-only JSON representation of a Python string
795-
796-    """
797-    if isinstance(s, str) and HAS_UTF8.search(s) is not None:
798-        s = s.decode('utf-8')
799-    def replace(match):
800-        s = match.group(0)
801-        try:
802-            return ESCAPE_DCT[s]
803-        except KeyError:
804-            n = ord(s)
805-            if n < 0x10000:
806-                return '\\u%04x' % (n,)
807-            else:
808-                # surrogate pair
809-                n -= 0x10000
810-                s1 = 0xd800 | ((n >> 10) & 0x3ff)
811-                s2 = 0xdc00 | (n & 0x3ff)
812-                return '\\u%04x\\u%04x' % (s1, s2)
813-    return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
814-
815-
816-encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
817-
818-class JSONEncoder(object):
819-    """Extensible JSON <http://json.org> encoder for Python data structures.
820-
821-    Supports the following objects and types by default:
822-
823-    +-------------------+---------------+
824-    | Python            | JSON          |
825-    +===================+===============+
826-    | dict              | object        |
827-    +-------------------+---------------+
828-    | list, tuple       | array         |
829-    +-------------------+---------------+
830-    | str, unicode      | string        |
831-    +-------------------+---------------+
832-    | int, long, float  | number        |
833-    +-------------------+---------------+
834-    | True              | true          |
835-    +-------------------+---------------+
836-    | False             | false         |
837-    +-------------------+---------------+
838-    | None              | null          |
839-    +-------------------+---------------+
840-
841-    To extend this to recognize other objects, subclass and implement a
842-    ``.default()`` method with another method that returns a serializable
843-    object for ``o`` if possible, otherwise it should call the superclass
844-    implementation (to raise ``TypeError``).
845-
846-    """
847-    item_separator = ', '
848-    key_separator = ': '
849-    def __init__(self, skipkeys=False, ensure_ascii=True,
850-            check_circular=True, allow_nan=True, sort_keys=False,
851-            indent=None, separators=None, encoding='utf-8', default=None):
852-        """Constructor for JSONEncoder, with sensible defaults.
853-
854-        If skipkeys is False, then it is a TypeError to attempt
855-        encoding of keys that are not str, int, long, float or None.  If
856-        skipkeys is True, such items are simply skipped.
857-
858-        If ensure_ascii is True, the output is guaranteed to be str
859-        objects with all incoming unicode characters escaped.  If
860-        ensure_ascii is false, the output will be unicode object.
861-
862-        If check_circular is True, then lists, dicts, and custom encoded
863-        objects will be checked for circular references during encoding to
864-        prevent an infinite recursion (which would cause an OverflowError).
865-        Otherwise, no such check takes place.
866-
867-        If allow_nan is True, then NaN, Infinity, and -Infinity will be
868-        encoded as such.  This behavior is not JSON specification compliant,
869-        but is consistent with most JavaScript based encoders and decoders.
870-        Otherwise, it will be a ValueError to encode such floats.
871-
872-        If sort_keys is True, then the output of dictionaries will be
873-        sorted by key; this is useful for regression tests to ensure
874-        that JSON serializations can be compared on a day-to-day basis.
875-
876-        If indent is a non-negative integer, then JSON array
877-        elements and object members will be pretty-printed with that
878-        indent level.  An indent level of 0 will only insert newlines.
879-        None is the most compact representation.
880-
881-        If specified, separators should be a (item_separator, key_separator)
882-        tuple.  The default is (', ', ': ').  To get the most compact JSON
883-        representation you should specify (',', ':') to eliminate whitespace.
884-
885-        If specified, default is a function that gets called for objects
886-        that can't otherwise be serialized.  It should return a JSON encodable
887-        version of the object or raise a ``TypeError``.
888-
889-        If encoding is not None, then all input strings will be
890-        transformed into unicode using that encoding prior to JSON-encoding.
891-        The default is UTF-8.
892-
893-        """
894-
895-        self.skipkeys = skipkeys
896-        self.ensure_ascii = ensure_ascii
897-        self.check_circular = check_circular
898-        self.allow_nan = allow_nan
899-        self.sort_keys = sort_keys
900-        self.indent = indent
901-        if separators is not None:
902-            self.item_separator, self.key_separator = separators
903-        if default is not None:
904-            self.default = default
905-        self.encoding = encoding
906-
907-    def default(self, o):
908-        """Implement this method in a subclass such that it returns
909-        a serializable object for ``o``, or calls the base implementation
910-        (to raise a ``TypeError``).
911-
912-        For example, to support arbitrary iterators, you could
913-        implement default like this::
914-
915-            def default(self, o):
916-                try:
917-                    iterable = iter(o)
918-                except TypeError:
919-                    pass
920-                else:
921-                    return list(iterable)
922-                return JSONEncoder.default(self, o)
923-
924-        """
925-        raise TypeError("%r is not JSON serializable" % (o,))
926-
927-    def encode(self, o):
928-        """Return a JSON string representation of a Python data structure.
929-
930-        >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
931-        '{"foo": ["bar", "baz"]}'
932-
933-        """
934-        # This is for extremely simple cases and benchmarks.
935-        if isinstance(o, basestring):
936-            if isinstance(o, str):
937-                _encoding = self.encoding
938-                if (_encoding is not None
939-                        and not (_encoding == 'utf-8')):
940-                    o = o.decode(_encoding)
941-            if self.ensure_ascii:
942-                return encode_basestring_ascii(o)
943-            else:
944-                return encode_basestring(o)
945-        # This doesn't pass the iterator directly to ''.join() because the
946-        # exceptions aren't as detailed.  The list call should be roughly
947-        # equivalent to the PySequence_Fast that ''.join() would do.
948-        chunks = self.iterencode(o, _one_shot=True)
949-        if not isinstance(chunks, (list, tuple)):
950-            chunks = list(chunks)
951-        return ''.join(chunks)
952-
953-    def iterencode(self, o, _one_shot=False):
954-        """Encode the given object and yield each string
955-        representation as available.
956-
957-        For example::
958-
959-            for chunk in JSONEncoder().iterencode(bigobject):
960-                mysocket.write(chunk)
961-
962-        """
963-        if self.check_circular:
964-            markers = {}
965-        else:
966-            markers = None
967-        if self.ensure_ascii:
968-            _encoder = encode_basestring_ascii
969-        else:
970-            _encoder = encode_basestring
971-        if self.encoding != 'utf-8':
972-            def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
973-                if isinstance(o, str):
974-                    o = o.decode(_encoding)
975-                return _orig_encoder(o)
976-
977-        def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
978-            # Check for specials.  Note that this type of test is processor- and/or
979-            # platform-specific, so do tests which don't depend on the internals.
980-
981-            if o != o:
982-                text = 'NaN'
983-            elif o == _inf:
984-                text = 'Infinity'
985-            elif o == _neginf:
986-                text = '-Infinity'
987-            else:
988-                return _repr(o)
989-
990-            if not allow_nan:
991-                raise ValueError("Out of range float values are not JSON compliant: %r"
992-                    % (o,))
993-
994-            return text
995-
996-
997-        if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
998-            _iterencode = c_make_encoder(
999-                markers, self.default, _encoder, self.indent,
1000-                self.key_separator, self.item_separator, self.sort_keys,
1001-                self.skipkeys, self.allow_nan)
1002-        else:
1003-            _iterencode = _make_iterencode(
1004-                markers, self.default, _encoder, self.indent, floatstr,
1005-                self.key_separator, self.item_separator, self.sort_keys,
1006-                self.skipkeys, _one_shot)
1007-        return _iterencode(o, 0)
1008-
1009-def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
1010-        ## HACK: hand-optimized bytecode; turn globals into locals
1011-        False=False,
1012-        True=True,
1013-        ValueError=ValueError,
1014-        basestring=basestring,
1015-        dict=dict,
1016-        float=float,
1017-        id=id,
1018-        int=int,
1019-        isinstance=isinstance,
1020-        list=list,
1021-        long=long,
1022-        str=str,
1023-        tuple=tuple,
1024-    ):
1025-
1026-    def _iterencode_list(lst, _current_indent_level):
1027-        if not lst:
1028-            yield '[]'
1029-            return
1030-        if markers is not None:
1031-            markerid = id(lst)
1032-            if markerid in markers:
1033-                raise ValueError("Circular reference detected")
1034-            markers[markerid] = lst
1035-        buf = '['
1036-        if _indent is not None:
1037-            _current_indent_level += 1
1038-            newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
1039-            separator = _item_separator + newline_indent
1040-            buf += newline_indent
1041-        else:
1042-            newline_indent = None
1043-            separator = _item_separator
1044-        first = True
1045-        for value in lst:
1046-            if first:
1047-                first = False
1048-            else:
1049-                buf = separator
1050-            if isinstance(value, basestring):
1051-                yield buf + _encoder(value)
1052-            elif value is None:
1053-                yield buf + 'null'
1054-            elif value is True:
1055-                yield buf + 'true'
1056-            elif value is False:
1057-                yield buf + 'false'
1058-            elif isinstance(value, (int, long)):
1059-                yield buf + str(value)
1060-            elif isinstance(value, float):
1061-                yield buf + _floatstr(value)
1062-            else:
1063-                yield buf
1064-                if isinstance(value, (list, tuple)):
1065-                    chunks = _iterencode_list(value, _current_indent_level)
1066-                elif isinstance(value, dict):
1067-                    chunks = _iterencode_dict(value, _current_indent_level)
1068-                else:
1069-                    chunks = _iterencode(value, _current_indent_level)
1070-                for chunk in chunks:
1071-                    yield chunk
1072-        if newline_indent is not None:
1073-            _current_indent_level -= 1
1074-            yield '\n' + (' ' * (_indent * _current_indent_level))
1075-        yield ']'
1076-        if markers is not None:
1077-            del markers[markerid]
1078-
1079-    def _iterencode_dict(dct, _current_indent_level):
1080-        if not dct:
1081-            yield '{}'
1082-            return
1083-        if markers is not None:
1084-            markerid = id(dct)
1085-            if markerid in markers:
1086-                raise ValueError("Circular reference detected")
1087-            markers[markerid] = dct
1088-        yield '{'
1089-        if _indent is not None:
1090-            _current_indent_level += 1
1091-            newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
1092-            item_separator = _item_separator + newline_indent
1093-            yield newline_indent
1094-        else:
1095-            newline_indent = None
1096-            item_separator = _item_separator
1097-        first = True
1098-        if _sort_keys:
1099-            items = dct.items()
1100-            items.sort(key=lambda kv: kv[0])
1101-        else:
1102-            items = dct.iteritems()
1103-        for key, value in items:
1104-            if isinstance(key, basestring):
1105-                pass
1106-            # JavaScript is weakly typed for these, so it makes sense to
1107-            # also allow them.  Many encoders seem to do something like this.
1108-            elif isinstance(key, float):
1109-                key = _floatstr(key)
1110-            elif isinstance(key, (int, long)):
1111-                key = str(key)
1112-            elif key is True:
1113-                key = 'true'
1114-            elif key is False:
1115-                key = 'false'
1116-            elif key is None:
1117-                key = 'null'
1118-            elif _skipkeys:
1119-                continue
1120-            else:
1121-                raise TypeError("key %r is not a string" % (key,))
1122-            if first:
1123-                first = False
1124-            else:
1125-                yield item_separator
1126-            yield _encoder(key)
1127-            yield _key_separator
1128-            if isinstance(value, basestring):
1129-                yield _encoder(value)
1130-            elif value is None:
1131-                yield 'null'
1132-            elif value is True:
1133-                yield 'true'
1134-            elif value is False:
1135-                yield 'false'
1136-            elif isinstance(value, (int, long)):
1137-                yield str(value)
1138-            elif isinstance(value, float):
1139-                yield _floatstr(value)
1140-            else:
1141-                if isinstance(value, (list, tuple)):
1142-                    chunks = _iterencode_list(value, _current_indent_level)
1143-                elif isinstance(value, dict):
1144-                    chunks = _iterencode_dict(value, _current_indent_level)
1145-                else:
1146-                    chunks = _iterencode(value, _current_indent_level)
1147-                for chunk in chunks:
1148-                    yield chunk
1149-        if newline_indent is not None:
1150-            _current_indent_level -= 1
1151-            yield '\n' + (' ' * (_indent * _current_indent_level))
1152-        yield '}'
1153-        if markers is not None:
1154-            del markers[markerid]
1155-
1156-    def _iterencode(o, _current_indent_level):
1157-        if isinstance(o, basestring):
1158-            yield _encoder(o)
1159-        elif o is None:
1160-            yield 'null'
1161-        elif o is True:
1162-            yield 'true'
1163-        elif o is False:
1164-            yield 'false'
1165-        elif isinstance(o, (int, long)):
1166-            yield str(o)
1167-        elif isinstance(o, float):
1168-            yield _floatstr(o)
1169-        elif isinstance(o, (list, tuple)):
1170-            for chunk in _iterencode_list(o, _current_indent_level):
1171-                yield chunk
1172-        elif isinstance(o, dict):
1173-            for chunk in _iterencode_dict(o, _current_indent_level):
1174-                yield chunk
1175-        else:
1176-            if markers is not None:
1177-                markerid = id(o)
1178-                if markerid in markers:
1179-                    raise ValueError("Circular reference detected")
1180-                markers[markerid] = o
1181-            o = _default(o)
1182-            for chunk in _iterencode(o, _current_indent_level):
1183-                yield chunk
1184-            if markers is not None:
1185-                del markers[markerid]
1186-
1187-    return _iterencode
1188diff --git a/django/utils/simplejson/scanner.py b/django/utils/simplejson/scanner.py
1189deleted file mode 100644
1190index adbc6ec..0000000
1191--- a/django/utils/simplejson/scanner.py
1192+++ /dev/null
1193@@ -1,65 +0,0 @@
1194-"""JSON token scanner
1195-"""
1196-import re
1197-try:
1198-    from simplejson._speedups import make_scanner as c_make_scanner
1199-except ImportError:
1200-    c_make_scanner = None
1201-
1202-__all__ = ['make_scanner']
1203-
1204-NUMBER_RE = re.compile(
1205-    r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
1206-    (re.VERBOSE | re.MULTILINE | re.DOTALL))
1207-
1208-def py_make_scanner(context):
1209-    parse_object = context.parse_object
1210-    parse_array = context.parse_array
1211-    parse_string = context.parse_string
1212-    match_number = NUMBER_RE.match
1213-    encoding = context.encoding
1214-    strict = context.strict
1215-    parse_float = context.parse_float
1216-    parse_int = context.parse_int
1217-    parse_constant = context.parse_constant
1218-    object_hook = context.object_hook
1219-
1220-    def _scan_once(string, idx):
1221-        try:
1222-            nextchar = string[idx]
1223-        except IndexError:
1224-            raise StopIteration
1225-
1226-        if nextchar == '"':
1227-            return parse_string(string, idx + 1, encoding, strict)
1228-        elif nextchar == '{':
1229-            return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook)
1230-        elif nextchar == '[':
1231-            return parse_array((string, idx + 1), _scan_once)
1232-        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
1233-            return None, idx + 4
1234-        elif nextchar == 't' and string[idx:idx + 4] == 'true':
1235-            return True, idx + 4
1236-        elif nextchar == 'f' and string[idx:idx + 5] == 'false':
1237-            return False, idx + 5
1238-
1239-        m = match_number(string, idx)
1240-        if m is not None:
1241-            integer, frac, exp = m.groups()
1242-            if frac or exp:
1243-                res = parse_float(integer + (frac or '') + (exp or ''))
1244-            else:
1245-                res = parse_int(integer)
1246-            return res, m.end()
1247-        elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
1248-            return parse_constant('NaN'), idx + 3
1249-        elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
1250-            return parse_constant('Infinity'), idx + 8
1251-        elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
1252-            return parse_constant('-Infinity'), idx + 9
1253-        else:
1254-            raise StopIteration
1255-
1256-    return _scan_once
1257-
1258-make_scanner = c_make_scanner or py_make_scanner
1259diff --git a/django/utils/simplejson/tool.py b/django/utils/simplejson/tool.py
1260deleted file mode 100644
1261index 74401c2..0000000
1262--- a/django/utils/simplejson/tool.py
1263+++ /dev/null
1264@@ -1,35 +0,0 @@
1265-r"""Using simplejson from the shell to validate and
1266-pretty-print::
1267-
1268-    $ echo '{"json":"obj"}' | python -msimplejson.tool
1269-    {
1270-        "json": "obj"
1271-    }
1272-    $ echo '{ 1.2:3.4}' | python -msimplejson.tool
1273-    Expecting property name: line 1 column 2 (char 2)
1274-"""
1275-from django.utils import simplejson
1276-
1277-def main():
1278-    import sys
1279-    if len(sys.argv) == 1:
1280-        infile = sys.stdin
1281-        outfile = sys.stdout
1282-    elif len(sys.argv) == 2:
1283-        infile = open(sys.argv[1], 'rb')
1284-        outfile = sys.stdout
1285-    elif len(sys.argv) == 3:
1286-        infile = open(sys.argv[1], 'rb')
1287-        outfile = open(sys.argv[2], 'wb')
1288-    else:
1289-        raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],))
1290-    try:
1291-        obj = simplejson.load(infile)
1292-    except ValueError, e:
1293-        raise SystemExit(e)
1294-    simplejson.dump(obj, outfile, sort_keys=True, indent=4)
1295-    outfile.write('\n')
1296-
1297-
1298-if __name__ == '__main__':
1299-    main()