Commit 792313d3 authored by SVN-Git Migration's avatar SVN-Git Migration

Imported Upstream version 3.1.0

parent 19457f49
Version 3.1.0 released 2013-02-21
* Updated JSON conformance test suite
http://bugs.python.org/issue16559
* simplejson.tool tests and bugfix for Python 3.x
http://bugs.python.org/issue16549
* Improve error messages for certain kinds of truncated input
http://bugs.python.org/issue16009
* Moved JSONDecodeError to json.scanner (still available for import
from json.decoder)
* Changed scanner to use JSONDecodeError directly rather than
StopIteration to improve error messages
Version 3.0.9 released 2013-02-21
* Fix an off-by-one error in the colno property of JSONDecodeError
(when lineno == 1)
http://bugs.python.org/issue17225
Version 3.0.8 released 2013-02-19
* Fix a Python 2.x compiler warning for narrow unicode builds
https://github.com/simplejson/simplejson/issues/56
Version 3.0.7 released 2013-01-11
* NOTE: this release only changes the license.
* simplejson is now dual-licensed software, MIT or AFL v2.1. It is
also made explicit that this code is also licensed to the PSF under
a Contributor Agreement.
Version 3.0.6 released 2013-01-11
* Fix for major Python 2.x ensure_ascii=False encoding regression
introduced in simplejson 3.0.0. If you use this setting, please
upgrade immediately.
https://github.com/simplejson/simplejson/issues/50
Version 3.0.5 released 2013-01-03
* NOTE: this release only changes the tests, it is
not essential to upgrade
* Tests now run with deprecation warnings printed
* Fixed Python 3 syntax error in simplejson.tool
https://github.com/simplejson/simplejson/issues/49
* Fixed Python 3.3 deprecation warnings in test suite
https://github.com/simplejson/simplejson/issues/48
Version 3.0.4 released 2013-01-02
* MSVC compatibility for Python 3.3
https://github.com/simplejson/simplejson/pull/47
Version 3.0.3 released 2013-01-01
* Fixes for bugs introduced in 3.0.2
* Fixes for Python 2.5 compatibility
* MSVC compatibility for Python 2.x
https://github.com/simplejson/simplejson/pull/46
Version 3.0.2 released 2013-01-01
* THIS VERSION HAS BEEN REMOVED
* Missed a changeset to _speedups.c in the 3.0.1 branch cut
Version 3.0.1 released 2013-01-01
* THIS VERSION HAS BEEN REMOVED
* Add accumulator optimization to encoder, equivalent to the usage of
`_Py_Accu` in the Python 3.3 json library. Only relevant if encoding
very large JSON documents.
Version 3.0.0 released 2012-12-30
* Python 3.3 is now supported, thanks to Vinay Sajip
https://github.com/simplejson/simplejson/issues/8
* `sort_keys`/`item_sort_key` now sort on the stringified verison of the
key, rather than the original object. This ensures that the sort
only compares string types and makes the behavior consistent between
Python 2.x and Python 3.x.
* Like other number types, Decimal instances used as keys are now
coerced to strings when use_decimal is True.
Version 2.6.2 released 2012-09-21
* JSONEncoderForHTML was not exported in the simplejson module
......
simplejson is dual-licensed software. It is available under the terms
of the MIT license, or the Academic Free License version 2.1. The full
text of each license agreement is included below. This code is also
licensed to the Python Software Foundation (PSF) under a Contributor
Agreement.
MIT License
===========
Copyright (c) 2006 Bob Ippolito
Permission is hereby granted, free of charge, to any person obtaining a copy of
......@@ -17,3 +26,54 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Academic Free License v. 2.1
============================
Copyright (c) 2006 Bob Ippolito. All rights reserved.
This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work:
Licensed under the Academic Free License version 2.1
1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following:
a) to reproduce the Original Work in copies;
b) to prepare derivative works ("Derivative Works") based upon the Original Work;
c) to distribute copies of the Original Work and Derivative Works to the public;
d) to perform the Original Work publicly; and
e) to display the Original Work publicly.
2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works.
3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work.
4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license.
5) This section intentionally omitted.
6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.
7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer.
8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions.
10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.
11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License.
12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.
13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.
14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.
This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner.
Metadata-Version: 1.0
Metadata-Version: 1.1
Name: simplejson
Version: 2.6.2
Version: 3.1.0
Summary: Simple, fast, extensible JSON encoder/decoder for Python
Home-page: http://github.com/simplejson/simplejson
Author: Bob Ippolito
Author-email: bob@redivi.com
License: MIT License
Description: simplejson is a simple, fast, complete, correct and extensible
JSON <http://json.org> encoder and decoder for Python 2.5+. It is
pure Python code with no dependencies, but includes an optional C
extension for a serious speed boost.
JSON <http://json.org> encoder and decoder for Python 2.5+
and Python 3.3+. It is pure Python code with no dependencies,
but includes an optional C extension for a serious speed boost.
The latest documentation for simplejson can be read online here:
http://simplejson.readthedocs.org/
......@@ -27,7 +27,17 @@ Description: simplejson is a simple, fast, complete, correct and extensible
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: License :: OSI Approved :: Academic Free License (AFL)
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.5
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Libraries :: Python Modules
simplejson is a simple, fast, complete, correct and extensible
JSON <http://json.org> encoder and decoder for Python 2.5+. It is
pure Python code with no dependencies, but includes an optional C
extension for a serious speed boost.
JSON <http://json.org> encoder and decoder for Python 2.5+
and Python 3.3+. It is pure Python code with no dependencies,
but includes an optional C extension for a serious speed boost.
The latest documentation for simplejson can be read online here:
http://simplejson.readthedocs.org/
......
......@@ -36,15 +36,15 @@ master_doc = 'index'
# General substitutions.
project = 'simplejson'
copyright = '2012, Bob Ippolito'
copyright = '2013, Bob Ippolito'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '2.6'
version = '3.1'
# The full version, including alpha/beta/rc tags.
release = '2.6.2'
release = '3.1'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
......
......@@ -14,7 +14,7 @@ syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
version of the :mod:`json` library contained in Python 2.6, but maintains
compatibility with Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
extension for speedups. :mod:`simplejson` is also supported on Python 3.3+.
Development of simplejson happens on Github:
http://github.com/simplejson/simplejson
......@@ -24,15 +24,15 @@ Encoding basic Python object hierarchies::
>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print json.dumps(u'\u1234')
>>> print(json.dumps(u'\u1234'))
"\u1234"
>>> print json.dumps('\\')
>>> print(json.dumps('\\'))
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> from simplejson.compat import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
......@@ -41,14 +41,15 @@ Encoding basic Python object hierarchies::
Compact encoding::
>>> import simplejson as json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':'))
>>> obj = [1,2,3,{'4': 5, '6': 7}]
>>> json.dumps(obj, separators=(',', ':'), sort_keys=True)
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4 * ' ')
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
>>> print('\n'.join([l.rstrip() for l in s.splitlines()]))
{
"4": 5,
"6": 7
......@@ -62,7 +63,7 @@ Decoding JSON::
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> from simplejson.compat import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
......@@ -116,7 +117,7 @@ Using :mod:`simplejson.tool` from the shell to validate and pretty-print::
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 2)
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
.. highlight:: python
......@@ -218,6 +219,11 @@ Basic Usage
will be sorted by key; this is useful for regression tests to ensure that
JSON serializations can be compared on a day-to-day basis.
.. versionchanged:: 3.0.0
Sorting now happens after the keys have been coerced to
strings, to avoid comparison of heterogeneously typed objects
(since this does not work in Python 3.3+)
If *item_sort_key* is a callable (not the default), then the output of
dictionaries will be sorted with it. The callable will be used like this:
``sorted(dct.items(), key=item_sort_key)``. This option takes precedence
......@@ -226,6 +232,11 @@ Basic Usage
.. versionchanged:: 2.5.0
*item_sort_key* is new in 2.5.0.
.. versionchanged:: 3.0.0
Sorting now happens after the keys have been coerced to
strings, to avoid comparison of heterogeneously typed objects
(since this does not work in Python 3.3+)
.. note::
JSON is not a framed protocol so unlike :mod:`pickle` or :mod:`marshal` it
......@@ -487,6 +498,11 @@ Encoders and decoders
will be sorted by key; this is useful for regression tests to ensure that
JSON serializations can be compared on a day-to-day basis.
.. versionchanged:: 3.0.0
Sorting now happens after the keys have been coerced to
strings, to avoid comparison of heterogeneously typed objects
(since this does not work in Python 3.3+)
If *item_sort_key* is a callable (not the default), then the output of
dictionaries will be sorted with it. The callable will be used like this:
``sorted(dct.items(), key=item_sort_key)``. This option takes precedence
......@@ -495,6 +511,11 @@ Encoders and decoders
.. versionchanged:: 2.5.0
*item_sort_key* is new in 2.5.0.
.. versionchanged:: 3.0.0
Sorting now happens after the keys have been coerced to
strings, to avoid comparison of heterogeneously typed objects
(since this does not work in Python 3.3+)
If *indent* is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated
for each level of nesting. ``None`` (the default) selects the most compact
......
#!/usr/bin/env python
from __future__ import with_statement
import sys
from distutils.core import setup, Extension, Command
......@@ -7,15 +8,27 @@ from distutils.errors import CCompilerError, DistutilsExecError, \
DistutilsPlatformError
IS_PYPY = hasattr(sys, 'pypy_translation_info')
VERSION = '2.6.2'
VERSION = '3.1.0'
DESCRIPTION = "Simple, fast, extensible JSON encoder/decoder for Python"
LONG_DESCRIPTION = open('README.rst', 'r').read()
with open('README.rst', 'r') as f:
LONG_DESCRIPTION = f.read()
CLASSIFIERS = filter(None, map(str.strip,
"""
Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: MIT License
License :: OSI Approved :: Academic Free License (AFL)
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 2.5
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: Implementation :: PyPy
Topic :: Software Development :: Libraries :: Python Modules
""".splitlines()))
......@@ -36,13 +49,13 @@ class ve_build_ext(build_ext):
def run(self):
try:
build_ext.run(self)
except DistutilsPlatformError, x:
except DistutilsPlatformError:
raise BuildFailed()
def build_extension(self, ext):
try:
build_ext.build_extension(self, ext)
except ext_errors, x:
except ext_errors:
raise BuildFailed()
......@@ -58,7 +71,10 @@ class TestCommand(Command):
def run(self):
import sys, subprocess
raise SystemExit(
subprocess.call([sys.executable, 'simplejson/tests/__init__.py']))
subprocess.call([sys.executable,
# Turn on deprecation warnings
'-Wd',
'simplejson/tests/__init__.py']))
def run_setup(with_binary):
cmdclass = dict(test=TestCommand)
......@@ -89,16 +105,17 @@ def run_setup(with_binary):
try:
run_setup(not IS_PYPY)
except BuildFailed:
BUILD_EXT_WARNING = "WARNING: The C extension could not be compiled, speedups are not enabled."
print '*' * 75
print BUILD_EXT_WARNING
print "Failure information, if any, is above."
print "I'm retrying the build without the C extension now."
print '*' * 75
BUILD_EXT_WARNING = ("WARNING: The C extension could not be compiled, "
"speedups are not enabled.")
print('*' * 75)
print(BUILD_EXT_WARNING)
print("Failure information, if any, is above.")
print("I'm retrying the build without the C extension now.")
print('*' * 75)
run_setup(False)
print '*' * 75
print BUILD_EXT_WARNING
print "Plain-Python installation succeeded."
print '*' * 75
print('*' * 75)
print(BUILD_EXT_WARNING)
print("Plain-Python installation succeeded.")
print('*' * 75)
......@@ -14,15 +14,15 @@ Encoding basic Python object hierarchies::
>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print json.dumps(u'\u1234')
>>> print(json.dumps(u'\u1234'))
"\u1234"
>>> print json.dumps('\\')
>>> print(json.dumps('\\'))
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> from simplejson.compat import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
......@@ -31,14 +31,15 @@ Encoding basic Python object hierarchies::
Compact encoding::
>>> import simplejson as json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
>>> obj = [1,2,3,{'4': 5, '6': 7}]
>>> json.dumps(obj, separators=(',',':'), sort_keys=True)
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ')
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
>>> print('\n'.join([l.rstrip() for l in s.splitlines()]))
{
"4": 5,
"6": 7
......@@ -52,7 +53,7 @@ Decoding JSON::
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> from simplejson.compat import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
......@@ -95,9 +96,10 @@ Using simplejson.tool from the shell to validate and pretty-print::
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name: line 1 column 2 (char 2)
Expecting property name: line 1 column 3 (char 2)
"""
__version__ = '2.6.2'
from __future__ import absolute_import
__version__ = '3.1.0'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
......@@ -108,20 +110,21 @@ __author__ = 'Bob Ippolito <bob@redivi.com>'
from decimal import Decimal
from decoder import JSONDecoder, JSONDecodeError
from encoder import JSONEncoder, JSONEncoderForHTML
from .scanner import JSONDecodeError
from .decoder import JSONDecoder
from .encoder import JSONEncoder, JSONEncoderForHTML
def _import_OrderedDict():
import collections
try:
return collections.OrderedDict
except AttributeError:
import ordered_dict
from . import ordered_dict
return ordered_dict.OrderedDict
OrderedDict = _import_OrderedDict()
def _import_c_make_encoder():
try:
from simplejson._speedups import make_encoder
from ._speedups import make_encoder
return make_encoder
except ImportError:
return None
......@@ -469,9 +472,9 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
def _toggle_speedups(enabled):
import simplejson.decoder as dec
import simplejson.encoder as enc
import simplejson.scanner as scan
from . import decoder as dec
from . import encoder as enc
from . import scanner as scan
c_make_encoder = _import_c_make_encoder()
if enabled:
dec.scanstring = dec.c_scanstring or dec.py_scanstring
......
This diff is collapsed.
"""Python 3 compatibility shims
"""
import sys
if sys.version_info[0] < 3:
PY3 = False
def b(s):
return s
def u(s):
return unicode(s, 'unicode_escape')
import cStringIO as StringIO
StringIO = BytesIO = StringIO.StringIO
text_type = unicode
binary_type = str
string_types = (basestring,)
integer_types = (int, long)
unichr = unichr
reload_module = reload
def fromhex(s):
return s.decode('hex')
else:
PY3 = True
from imp import reload as reload_module
import codecs
def b(s):
return codecs.latin_1_encode(s)[0]
def u(s):
return s
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
text_type = str
binary_type = bytes
string_types = (str,)
integer_types = (int,)
def unichr(s):
return u(chr(s))
def fromhex(s):
return bytes.fromhex(s)
long_type = integer_types[-1]
This diff is collapsed.
This diff is collapsed.
......@@ -9,12 +9,59 @@ def _import_c_make_scanner():
return None
c_make_scanner = _import_c_make_scanner()
__all__ = ['make_scanner']
__all__ = ['make_scanner', 'JSONDecodeError']
NUMBER_RE = re.compile(
r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
(re.VERBOSE | re.MULTILINE | re.DOTALL))
class JSONDecodeError(ValueError):
"""Subclass of ValueError with the following additional properties:
msg: The unformatted error message
doc: The JSON document being parsed
pos: The start index of doc where parsing failed
end: The end index of doc where parsing failed (may be None)
lineno: The line corresponding to pos
colno: The column corresponding to pos
endlineno: The line corresponding to end (may be None)
endcolno: The column corresponding to end (may be None)
"""
# Note that this exception is used from _speedups
def __init__(self, msg, doc, pos, end=None):
ValueError.__init__(self, errmsg(msg, doc, pos, end=end))
self.msg = msg
self.doc = doc
self.pos = pos
self.end = end
self.lineno, self.colno = linecol(doc, pos)
if end is not None:
self.endlineno, self.endcolno = linecol(doc, end)
else:
self.endlineno, self.endcolno = None, None
def linecol(doc, pos):
lineno = doc.count('\n', 0, pos) + 1
if lineno == 1:
colno = pos + 1
else:
colno = pos - doc.rindex('\n', 0, pos)
return lineno, colno
def errmsg(msg, doc, pos, end=None):
lineno, colno = linecol(doc, pos)
msg = msg.replace('%r', repr(doc[pos:pos + 1]))
if end is None:
fmt = '%s: line %d column %d (char %d)'
return fmt % (msg, lineno, colno, pos)
endlineno, endcolno = linecol(doc, end)
fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
def py_make_scanner(context):
parse_object = context.parse_object
parse_array = context.parse_array
......@@ -30,10 +77,11 @@ def py_make_scanner(context):
memo = context.memo
def _scan_once(string, idx):
errmsg = 'Expecting value'
try:
nextchar = string[idx]
except IndexError:
raise StopIteration
raise JSONDecodeError(errmsg, string, idx)
if nextchar == '"':
return parse_string(string, idx + 1, encoding, strict)
......@@ -64,7 +112,7 @@ def py_make_scanner(context):
elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
return parse_constant('-Infinity'), idx + 9
else:
raise StopIteration
raise JSONDecodeError(errmsg, string, idx)
def scan_once(string, idx):
try:
......
from __future__ import absolute_import
import unittest
import doctest
import sys
class OptionalExtensionTestSuite(unittest.TestSuite):
def run(self, result):
import simplejson
run = unittest.TestSuite.run
run(self, result)
simplejson._toggle_speedups(False)
run(self, result)
simplejson._toggle_speedups(True)
if simplejson._import_c_make_encoder() is None:
TestMissingSpeedups().run(result)
else:
simplejson._toggle_speedups(False)
run(self, result)
simplejson._toggle_speedups(True)
return result
class TestMissingSpeedups(unittest.TestCase):
def runTest(self):
if hasattr(sys, 'pypy_translation_info'):
"PyPy doesn't need speedups! :)"
elif hasattr(self, 'skipTest'):
self.skipTest('_speedups.so is missing!')
def additional_tests(suite=None):
import simplejson
......@@ -49,13 +59,14 @@ def all_tests_suite():
'simplejson.tests.test_decimal',
'simplejson.tests.test_tuple',
'simplejson.tests.test_namedtuple',
'simplejson.tests.test_tool',
])
suite = additional_tests(suite)
return OptionalExtensionTestSuite([suite])
def main():
runner = unittest.TextTestRunner()
runner = unittest.TextTestRunner(verbosity=1 + sys.argv.count('-v'))
suite = all_tests_suite()
raise SystemExit(not runner.run(suite).wasSuccessful())
......
from unittest import TestCase
import simplejson as json
from simplejson.compat import long_type
class TestBigintAsString(TestCase):
# Python 2.5, at least the one that ships on Mac OS X, calculates
# 2 ** 53 as 0! It manages to calculate 1 << 53 correctly.
values = [(200, 200),
((2 ** 53) - 1, 9007199254740991),
((2 ** 53), '9007199254740992'),
((2 ** 53) + 1, '9007199254740993'),
((1 << 53) - 1, 9007199254740991),
((1 << 53), '9007199254740992'),
((1 << 53) + 1, '9007199254740993'),
(-100, -100),
((-2 ** 53), '-9007199254740992'),
((-2 ** 53) - 1, '-9007199254740993'),
((-2 ** 53) + 1, -9007199254740991)]
((-1 << 53), '-9007199254740992'),
((-1 << 53) - 1, '-9007199254740993'),
((-1 << 53) + 1, -9007199254740991)]
def test_ints(self):
for val, expect in self.values:
self.assertEquals(
self.assertEqual(
val,
json.loads(json.dumps(val)))
self.assertEquals(
self.assertEqual(
expect,
json.loads(json.dumps(val, bigint_as_string=True)))
......@@ -25,10 +28,10 @@ class TestBigintAsString(TestCase):
for val, expect in self.values:
val = [val, val]
expect = [expect, expect]
self.assertEquals(
self.assertEqual(
val,
json.loads(json.dumps(val)))
self.assertEquals(
self.assertEqual(
expect,
json.loads(json.dumps(val, bigint_as_string=True)))
......@@ -36,10 +39,10 @@ class TestBigintAsString(TestCase):
for val, expect in self.values:
val = {'k': val}