Skip to content
Snippets Groups Projects
Commit 2e0e02fc3857 authored by Nick Babcock's avatar Nick Babcock
Browse files

Merge branch 'master' into iterable_as_array-gh1

Conflicts:
	CHANGES.txt
	conf.py
	index.rst
	setup.py
	simplejson/__init__.py
	simplejson/_speedups.c
	simplejson/encoder.py
	simplejson/tests/test_tuple.py
No related branches found
No related tags found
No related merge requests found
Showing
with 2975 additions and 1007 deletions
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
*.egg *.egg
*.pyc *.pyc
*.so *.so
.DS_Store
/MANIFEST /MANIFEST
/.coverage /.coverage
/coverage.xml /coverage.xml
...@@ -5,6 +6,7 @@ ...@@ -5,6 +6,7 @@
/MANIFEST /MANIFEST
/.coverage /.coverage
/coverage.xml /coverage.xml
/htmlcov
/build /build
/dist /dist
/docs /docs
language: python
python:
- "2.6"
- "2.7"
- "3.3"
- "3.4"
- "pypy"
script:
- python setup.py build_ext -i
- python -m compileall -f .
- python setup.py test
Version 2.3.0 released 2011-XX-XX Version 3.7.4 released 2015-XX-XX
* New iterable_as_array encoder option to perform lazy serialization of * New iterable_as_array encoder option to perform lazy serialization of
any iterable objects, without having to convert to tuple or list. any iterable objects, without having to convert to tuple or list.
...@@ -2,7 +2,288 @@ ...@@ -2,7 +2,288 @@
* New iterable_as_array encoder option to perform lazy serialization of * New iterable_as_array encoder option to perform lazy serialization of
any iterable objects, without having to convert to tuple or list. any iterable objects, without having to convert to tuple or list.
Version 3.7.3 released 2015-05-31
* Fix typo introduced in 3.7.0 (behavior should be indistinguishable)
https://github.com/simplejson/simplejson/commit/e18cc09b688ea1f3305c27616fd3cadd2adc6d31#commitcomment-11443842
Version 3.7.2 released 2015-05-22
* Do not cache Decimal class in encoder, only reference the decimal module.
This may make reload work in more common scenarios.
Version 3.7.1 released 2015-05-18
* Fix compilation with MSVC
https://github.com/simplejson/simplejson/pull/119
Version 3.7.0 released 2015-05-18
* simplejson no longer trusts custom str/repr methods for int, long, float
subclasses. These instances are now formatted as if they were exact
instances of those types.
https://github.com/simplejson/simplejson/issues/118
Version 3.6.5 released 2014-10-24
* Importing bug fix for reference leak when an error occurs during
dict encoding
https://github.com/simplejson/simplejson/issues/109
Version 3.6.4 released 2014-09-29
* Important bug fix for dump when only sort_keys is set
https://github.com/simplejson/simplejson/issues/106
Version 3.6.3 released 2014-08-18
* Documentation updates
https://github.com/simplejson/simplejson/issues/103
Version 3.6.2 released 2014-08-09
* Documentation updates
http://bugs.python.org/issue21514
Version 3.6.1 released 2014-08-09
* Documentation updates
https://github.com/simplejson/simplejson/issues/102
Version 3.6.0 released 2014-07-21
* Automatically strip any UTF-8 BOM from input to more closely
follow the latest specs
https://github.com/simplejson/simplejson/pull/101
Version 3.5.3 released 2014-06-24
* Fix lower bound checking in scan_once / raw_decode API
https://github.com/simplejson/simplejson/issues/98
Version 3.5.2 released 2014-05-22
* Fix Windows build with VS2008
https://github.com/simplejson/simplejson/pull/97
Version 3.5.1 released 2014-05-21
* Consistently reject int_as_string_bitcount settings that are not
positive integers
Version 3.5.0 released 2014-05-20
* Added int_as_string_bitcount encoder option
https://github.com/simplejson/pull/96
* Fixed potential crash when encoder created with incorrect options
Version 3.4.1 released 2014-04-30
* Fixed tests to run on Python 3.4
Version 3.4.0 released 2014-04-02
* Native setuptools support re-introduced
https://github.com/simplejson/simplejson/pull/92
Version 3.3.3 released 2014-02-14
* Improve test suite's Python 3.4 compatibility
https://github.com/simplejson/simplejson/issues/87
Version 3.3.2 released 2014-01-06
* Docstring fix for decoded string types
https://github.com/simplejson/simplejson/pull/82
Version 3.3.1 released 2013-10-05
* JSONDecodeError exceptions can now be pickled
https://github.com/simplejson/simplejson/pull/78
Version 3.3.0 released 2013-05-07
* Unpaired surrogates once again pass through the decoder, to match older
behavior and the RFC-4627 spec.
https://github.com/simplejson/simplejson/issues/62
Version 3.2.0 released 2013-05-01
* New ignore_nan kwarg in encoder that serializes out
of range floats (Infinity, -Infinity, NaN) as null for ECMA-262
compliance.
https://github.com/simplejson/simplejson/pull/63
* New for_json kwarg in encoder to make it possible to for
subclasses of dict and list to be specialized.
https://github.com/simplejson/simplejson/pull/69
Version 3.1.3 released 2013-04-06
* Updated documentation to discourage subclassing whenever possible.
default, object_hook, and object_pairs_hook provide almost all of
the functionality of subclassing.
Version 3.1.2 released 2013-03-20
* Updated documentation to reflect separators behavior when indent is
not None
https://github.com/simplejson/simplejson/issues/59
* Test suite should be compatible with debug builds of Python 2.x and 3.x
https://github.com/simplejson/simplejson/pull/65
Version 3.1.1 released 2013-02-21
* setup.py now has another workaround for Windows machines without
MSVC installed
http://bugs.python.org/issue7511
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
https://github.com/simplejson/simplejson/issues/41
Version 2.6.1 released 2012-07-27
* raw_decode() now skips whitespace before the object
https://github.com/simplejson/simplejson/pull/38
Version 2.6.0 released 2012-06-26
* Error messages changed to match proposal for Python 3.3.1
http://bugs.python.org/issue5067
Version 2.5.2 released 2012-05-10
* Fix for regression introduced in 2.5.1
https://github.com/simplejson/simplejson/issues/35
Version 2.5.1 released 2012-05-10
* Support for use_decimal=True in environments that use Python
sub-interpreters such as uWSGI
https://github.com/simplejson/simplejson/issues/34
Version 2.5.0 released 2012-03-29
* New item_sort_key option for encoder to allow fine grained control of sorted
output
Version 2.4.0 released 2012-03-06
* New bigint_as_string option for encoder to trade JavaScript number precision
issues for type issues.
https://github.com/simplejson/simplejson/issues/31
Version 2.3.3 released 2012-02-27
* Allow unknown numerical types for indent parameter
https://github.com/simplejson/simplejson/pull/29
Version 2.3.2 released 2011-12-30
* Fix crashing regression in speedups introduced in 2.3.1
Version 2.3.1 released 2011-12-29
* namedtuple_as_object now checks _asdict to ensure that it
is callable.
https://github.com/simplejson/simplejson/issues/26
Version 2.3.0 released 2011-12-05
* Any objects with _asdict() methods are now considered for
namedtuple_as_object.
https://github.com/simplejson/simplejson/pull/22
Version 2.2.1 released 2011-09-06
* Fix MANIFEST.in issue when building a sdist from a sdist.
https://github.com/simplejson/simplejson/issues/16
Version 2.2.0 released 2011-09-04 Version 2.2.0 released 2011-09-04
* Remove setuptools requirement, reverted to pure distutils * Remove setuptools requirement, reverted to pure distutils
......
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 Copyright (c) 2006 Bob Ippolito
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
...@@ -17,3 +26,54 @@ ...@@ -17,3 +26,54 @@
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. 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.
...@@ -2,3 +2,4 @@ ...@@ -2,3 +2,4 @@
include *.txt include *.txt
include *.rst include *.rst
include scripts/*.py include scripts/*.py
include MANIFEST.in
simplejson is a simple, fast, complete, correct and extensible simplejson is a simple, fast, complete, correct and extensible
JSON <http://json.org> encoder and decoder for Python 2.5+. It is JSON <http://json.org> encoder and decoder for Python 2.5+
pure Python code with no dependencies, but includes an optional C and Python 3.3+. It is pure Python code with no dependencies,
extension for a serious speed boost. but includes an optional C extension for a serious speed boost.
The latest documentation for simplejson can be read online here: The latest documentation for simplejson can be read online here:
http://simplejson.readthedocs.org/ http://simplejson.readthedocs.org/
...@@ -10,5 +10,5 @@ ...@@ -10,5 +10,5 @@
json library included with Python 2.6 and Python 3.0, but maintains json library included with Python 2.6 and Python 3.0, but maintains
backwards compatibility with Python 2.5. backwards compatibility with Python 2.5.
The encoder may be subclassed to provide serialization in any kind of The encoder can be specialized to provide serialization in any kind of
situation, without any special support by the objects to be serialized situation, without any special support by the objects to be serialized
...@@ -14,4 +14,5 @@ ...@@ -14,4 +14,5 @@
situation, without any special support by the objects to be serialized situation, without any special support by the objects to be serialized
(somewhat like pickle). (somewhat like pickle). This is best done with the ``default`` kwarg
to dumps.
The decoder can handle incoming JSON strings of any specified encoding The decoder can handle incoming JSON strings of any specified encoding
...@@ -16,4 +17,7 @@ ...@@ -16,4 +17,7 @@
The decoder can handle incoming JSON strings of any specified encoding The decoder can handle incoming JSON strings of any specified encoding
(UTF-8 by default). (UTF-8 by default). It can also be specialized to post-process JSON
objects with the ``object_hook`` or ``object_pairs_hook`` kwargs. This
is particularly useful for implementing protocols such as JSON-RPC
that have a richer type system than JSON itself.
...@@ -19,1 +23,7 @@ ...@@ -19,1 +23,7 @@
For those of you that have legacy systems to maintain, there is a
very old fork of simplejson in the `python2.2`_ branch that supports
Python 2.2. This is based off of a very old version of simplejson,
is not maintained, and should only be used as a last resort.
.. _python2.2: https://github.com/simplejson/simplejson/tree/python2.2
...@@ -36,9 +36,9 @@ ...@@ -36,9 +36,9 @@
# General substitutions. # General substitutions.
project = 'simplejson' project = 'simplejson'
copyright = '2011, Bob Ippolito' copyright = '2015, Bob Ippolito'
# The default replacements for |version| and |release|, also used in various # The default replacements for |version| and |release|, also used in various
# other places throughout the built documents. # other places throughout the built documents.
# #
# The short X.Y version. # The short X.Y version.
...@@ -40,7 +40,7 @@ ...@@ -40,7 +40,7 @@
# The default replacements for |version| and |release|, also used in various # The default replacements for |version| and |release|, also used in various
# other places throughout the built documents. # other places throughout the built documents.
# #
# The short X.Y version. # The short X.Y version.
version = '2.3' version = '3.7'
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
...@@ -46,5 +46,5 @@ ...@@ -46,5 +46,5 @@
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = '2.3.0' release = '3.7.4'
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
......
This diff is collapsed.
#!/usr/bin/env python #!/usr/bin/env python
from __future__ import with_statement
import sys import sys
...@@ -2,8 +3,11 @@ ...@@ -2,8 +3,11 @@
import sys import sys
try:
from setuptools import setup, Extension, Command
except ImportError:
from distutils.core import setup, Extension, Command from distutils.core import setup, Extension, Command
from distutils.command.build_ext import build_ext from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError, DistutilsExecError, \ from distutils.errors import CCompilerError, DistutilsExecError, \
DistutilsPlatformError DistutilsPlatformError
IS_PYPY = hasattr(sys, 'pypy_translation_info') IS_PYPY = hasattr(sys, 'pypy_translation_info')
...@@ -4,8 +8,8 @@ ...@@ -4,8 +8,8 @@
from distutils.core import setup, Extension, Command from distutils.core import setup, Extension, Command
from distutils.command.build_ext import build_ext from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError, DistutilsExecError, \ from distutils.errors import CCompilerError, DistutilsExecError, \
DistutilsPlatformError DistutilsPlatformError
IS_PYPY = hasattr(sys, 'pypy_translation_info') IS_PYPY = hasattr(sys, 'pypy_translation_info')
VERSION = '2.3.0' VERSION = '3.7.4'
DESCRIPTION = "Simple, fast, extensible JSON encoder/decoder for Python" DESCRIPTION = "Simple, fast, extensible JSON encoder/decoder for Python"
...@@ -11,5 +15,7 @@ ...@@ -11,5 +15,7 @@
DESCRIPTION = "Simple, fast, extensible JSON encoder/decoder for Python" 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, CLASSIFIERS = filter(None, map(str.strip,
""" """
...@@ -13,5 +19,6 @@ ...@@ -13,5 +19,6 @@
CLASSIFIERS = filter(None, map(str.strip, CLASSIFIERS = filter(None, map(str.strip,
""" """
Development Status :: 5 - Production/Stable
Intended Audience :: Developers Intended Audience :: Developers
License :: OSI Approved :: MIT License License :: OSI Approved :: MIT License
...@@ -16,3 +23,4 @@ ...@@ -16,3 +23,4 @@
Intended Audience :: Developers Intended Audience :: Developers
License :: OSI Approved :: MIT License License :: OSI Approved :: MIT License
License :: OSI Approved :: Academic Free License (AFL)
Programming Language :: Python Programming Language :: Python
...@@ -18,7 +26,16 @@ ...@@ -18,7 +26,16 @@
Programming Language :: Python 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 :: 3.4
Programming Language :: Python :: Implementation :: CPython
Programming Language :: Python :: Implementation :: PyPy
Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Libraries :: Python Modules
""".splitlines())) """.splitlines()))
if sys.platform == 'win32' and sys.version_info > (2, 6): if sys.platform == 'win32' and sys.version_info > (2, 6):
# 2.6's distutils.msvc9compiler can raise an IOError when failing to # 2.6's distutils.msvc9compiler can raise an IOError when failing to
# find the compiler # find the compiler
...@@ -19,7 +36,8 @@ ...@@ -19,7 +36,8 @@
Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Libraries :: Python Modules
""".splitlines())) """.splitlines()))
if sys.platform == 'win32' and sys.version_info > (2, 6): if sys.platform == 'win32' and sys.version_info > (2, 6):
# 2.6's distutils.msvc9compiler can raise an IOError when failing to # 2.6's distutils.msvc9compiler can raise an IOError when failing to
# find the compiler # find the compiler
# It can also raise ValueError http://bugs.python.org/issue7511
ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError, ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError,
...@@ -25,5 +43,5 @@ ...@@ -25,5 +43,5 @@
ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError, ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError,
IOError) IOError, ValueError)
else: else:
ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError)
...@@ -58,7 +76,10 @@ ...@@ -58,7 +76,10 @@
def run(self): def run(self):
import sys, subprocess import sys, subprocess
raise SystemExit( 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): def run_setup(with_binary):
cmdclass = dict(test=TestCommand) cmdclass = dict(test=TestCommand)
...@@ -89,12 +110,13 @@ ...@@ -89,12 +110,13 @@
try: try:
run_setup(not IS_PYPY) run_setup(not IS_PYPY)
except BuildFailed: except BuildFailed:
BUILD_EXT_WARNING = "WARNING: The C extension could not be compiled, speedups are not enabled." BUILD_EXT_WARNING = ("WARNING: The C extension could not be compiled, "
print '*' * 75 "speedups are not enabled.")
print BUILD_EXT_WARNING print('*' * 75)
print "Failure information, if any, is above." print(BUILD_EXT_WARNING)
print "I'm retrying the build without the C extension now." print("Failure information, if any, is above.")
print '*' * 75 print("I'm retrying the build without the C extension now.")
print('*' * 75)
run_setup(False) run_setup(False)
...@@ -98,7 +120,7 @@ ...@@ -98,7 +120,7 @@
run_setup(False) run_setup(False)
print '*' * 75 print('*' * 75)
print BUILD_EXT_WARNING print(BUILD_EXT_WARNING)
print "Plain-Python installation succeeded." print("Plain-Python installation succeeded.")
print '*' * 75 print('*' * 75)
...@@ -13,5 +13,5 @@ ...@@ -13,5 +13,5 @@
>>> import simplejson as json >>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]' '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar") >>> print(json.dumps("\"foo\bar"))
"\"foo\bar" "\"foo\bar"
...@@ -17,3 +17,3 @@ ...@@ -17,3 +17,3 @@
"\"foo\bar" "\"foo\bar"
>>> print json.dumps(u'\u1234') >>> print(json.dumps(u'\u1234'))
"\u1234" "\u1234"
...@@ -19,3 +19,3 @@ ...@@ -19,3 +19,3 @@
"\u1234" "\u1234"
>>> print json.dumps('\\') >>> print(json.dumps('\\'))
"\\" "\\"
...@@ -21,3 +21,3 @@ ...@@ -21,3 +21,3 @@
"\\" "\\"
>>> 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} {"a": 0, "b": 0, "c": 0}
...@@ -23,5 +23,5 @@ ...@@ -23,5 +23,5 @@
{"a": 0, "b": 0, "c": 0} {"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO >>> from simplejson.compat import StringIO
>>> io = StringIO() >>> io = StringIO()
>>> json.dump(['streaming API'], io) >>> json.dump(['streaming API'], io)
>>> io.getvalue() >>> io.getvalue()
...@@ -30,9 +30,10 @@ ...@@ -30,9 +30,10 @@
Compact encoding:: Compact encoding::
>>> import simplejson as json >>> 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}]' '[1,2,3,{"4":5,"6":7}]'
Pretty printing:: Pretty printing::
>>> import simplejson as json >>> import simplejson as json
...@@ -34,10 +35,9 @@ ...@@ -34,10 +35,9 @@
'[1,2,3,{"4":5,"6":7}]' '[1,2,3,{"4":5,"6":7}]'
Pretty printing:: Pretty printing::
>>> import simplejson as json >>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ') >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' '))
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
{ {
"4": 5, "4": 5,
"6": 7 "6": 7
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
True True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True True
>>> from StringIO import StringIO >>> from simplejson.compat import StringIO
>>> io = StringIO('["streaming API"]') >>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API' >>> json.load(io)[0] == 'streaming API'
True True
...@@ -94,5 +94,5 @@ ...@@ -94,5 +94,5 @@
"json": "obj" "json": "obj"
} }
$ echo '{ 1.2:3.4}' | python -m simplejson.tool $ 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)
""" """
...@@ -98,5 +98,6 @@ ...@@ -98,5 +98,6 @@
""" """
__version__ = '2.3.0' from __future__ import absolute_import
__version__ = '3.7.4'
__all__ = [ __all__ = [
'dump', 'dumps', 'load', 'loads', 'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
...@@ -100,10 +101,10 @@ ...@@ -100,10 +101,10 @@
__all__ = [ __all__ = [
'dump', 'dumps', 'load', 'loads', 'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
'OrderedDict', 'OrderedDict', 'simple_first',
] ]
__author__ = 'Bob Ippolito <bob@redivi.com>' __author__ = 'Bob Ippolito <bob@redivi.com>'
from decimal import Decimal from decimal import Decimal
...@@ -104,13 +105,14 @@ ...@@ -104,13 +105,14 @@
] ]
__author__ = 'Bob Ippolito <bob@redivi.com>' __author__ = 'Bob Ippolito <bob@redivi.com>'
from decimal import Decimal from decimal import Decimal
from decoder import JSONDecoder, JSONDecodeError from .scanner import JSONDecodeError
from encoder import JSONEncoder from .decoder import JSONDecoder
from .encoder import JSONEncoder, JSONEncoderForHTML
def _import_OrderedDict(): def _import_OrderedDict():
import collections import collections
try: try:
return collections.OrderedDict return collections.OrderedDict
except AttributeError: except AttributeError:
...@@ -112,11 +114,11 @@ ...@@ -112,11 +114,11 @@
def _import_OrderedDict(): def _import_OrderedDict():
import collections import collections
try: try:
return collections.OrderedDict return collections.OrderedDict
except AttributeError: except AttributeError:
import ordered_dict from . import ordered_dict
return ordered_dict.OrderedDict return ordered_dict.OrderedDict
OrderedDict = _import_OrderedDict() OrderedDict = _import_OrderedDict()
def _import_c_make_encoder(): def _import_c_make_encoder():
try: try:
...@@ -118,9 +120,9 @@ ...@@ -118,9 +120,9 @@
return ordered_dict.OrderedDict return ordered_dict.OrderedDict
OrderedDict = _import_OrderedDict() OrderedDict = _import_OrderedDict()
def _import_c_make_encoder(): def _import_c_make_encoder():
try: try:
from simplejson._speedups import make_encoder from ._speedups import make_encoder
return make_encoder return make_encoder
except ImportError: except ImportError:
return None return None
...@@ -138,9 +140,14 @@ ...@@ -138,9 +140,14 @@
namedtuple_as_object=True, namedtuple_as_object=True,
tuple_as_array=True, tuple_as_array=True,
iterable_as_array=False, iterable_as_array=False,
bigint_as_string=False,
item_sort_key=None,
for_json=False,
ignore_nan=False,
int_as_string_bitcount=None,
) )
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None, allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True, encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True, namedtuple_as_object=True, tuple_as_array=True,
...@@ -141,11 +148,12 @@ ...@@ -141,11 +148,12 @@
) )
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None, allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True, encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True, namedtuple_as_object=True, tuple_as_array=True,
iterable_as_array=False, bigint_as_string=False, sort_keys=False, item_sort_key=None,
**kw): for_json=False, ignore_nan=False, int_as_string_bitcount=None,
iterable_as_array=False, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object). ``.write()``-supporting file-like object).
...@@ -149,7 +157,7 @@ ...@@ -149,7 +157,7 @@
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object). ``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types If *skipkeys* is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``. will be skipped instead of raising a ``TypeError``.
...@@ -153,9 +161,9 @@ ...@@ -153,9 +161,9 @@
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``. will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the some chunks written to ``fp`` If *ensure_ascii* is false, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error. to cause an error.
...@@ -157,9 +165,9 @@ ...@@ -157,9 +165,9 @@
may be ``unicode`` instances, subject to normal Python ``str`` to may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error. to cause an error.
If ``check_circular`` is false, then the circular reference check If *check_circular* is false, then the circular reference check
for container types will be skipped and a circular reference will for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse). result in an ``OverflowError`` (or worse).
...@@ -163,5 +171,5 @@ ...@@ -163,5 +171,5 @@
for container types will be skipped and a circular reference will for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse). result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to If *allow_nan* is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
...@@ -167,6 +175,7 @@ ...@@ -167,6 +175,7 @@
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the in strict compliance of the original JSON specification, instead of using
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See
*ignore_nan* for ECMA-262 compliant behavior.
If *indent* is a string, then JSON array elements and object members If *indent* is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated will be pretty-printed with a newline followed by that string repeated
...@@ -175,7 +184,9 @@ ...@@ -175,7 +184,9 @@
versions of simplejson earlier than 2.1.0, an integer is also accepted versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces. and is converted to a string with that many spaces.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple If specified, *separators* should be an
then it will be used instead of the default ``(', ', ': ')`` separators. ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``
``(',', ':')`` is the most compact JSON representation. if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most
compact JSON representation, you should specify ``(',', ':')`` to eliminate
whitespace.
...@@ -181,3 +192,3 @@ ...@@ -181,3 +192,3 @@
``encoding`` is the character encoding for str instances, default is UTF-8. *encoding* is the character encoding for str instances, default is UTF-8.
...@@ -183,6 +194,6 @@ ...@@ -183,6 +194,6 @@
``default(obj)`` is a function that should return a serializable version *default(obj)* is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError. of obj or raise ``TypeError``. The default simply raises ``TypeError``.
If *use_decimal* is true (default: ``True``) then decimal.Decimal If *use_decimal* is true (default: ``True``) then decimal.Decimal
will be natively serialized to JSON with full precision. will be natively serialized to JSON with full precision.
...@@ -198,5 +209,32 @@ ...@@ -198,5 +209,32 @@
any object not in the above table that implements ``__iter__()`` any object not in the above table that implements ``__iter__()``
will be encoded as a JSON array. will be encoded as a JSON array.
If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise. Note that this is still a
lossy operation that will not round-trip correctly and should be used
sparingly.
If *int_as_string_bitcount* is a positive number (n), then int of size
greater than or equal to 2**n or lower than or equal to -2**n will be
encoded as strings.
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precedence over
*sort_keys*.
If *sort_keys* is true (default: ``False``), the output of dictionaries
will be sorted by item.
If *for_json* is true (default: ``False``), objects with a ``for_json()``
method will use the return value of that method for encoding as JSON
instead of the object.
If *ignore_nan* is true (default: ``False``), then out of range
:class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as
``null`` in compliance with the ECMA-262 specification. If true, this will
override *allow_nan*.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with ``.default()`` method to serialize additional types), specify it with
...@@ -201,9 +239,10 @@ ...@@ -201,9 +239,10 @@
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with ``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg. the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead
of subclassing whenever possible.
""" """
# cached encoder # cached encoder
if (not skipkeys and ensure_ascii and if (not skipkeys and ensure_ascii and
check_circular and allow_nan and check_circular and allow_nan and
cls is None and indent is None and separators is None and cls is None and indent is None and separators is None and
...@@ -204,12 +243,16 @@ ...@@ -204,12 +243,16 @@
""" """
# cached encoder # cached encoder
if (not skipkeys and ensure_ascii and if (not skipkeys and ensure_ascii and
check_circular and allow_nan and check_circular and allow_nan and
cls is None and indent is None and separators is None and cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal and encoding == 'utf-8' and default is None and use_decimal
namedtuple_as_object and tuple_as_array and and namedtuple_as_object and tuple_as_array and not iterable_as_array
not iterable_as_array and not kw): and not bigint_as_string and not sort_keys
and not item_sort_key and not for_json
and not ignore_nan and int_as_string_bitcount is None
and not kw
):
iterable = _default_encoder.iterencode(obj) iterable = _default_encoder.iterencode(obj)
else: else:
if cls is None: if cls is None:
...@@ -221,6 +264,12 @@ ...@@ -221,6 +264,12 @@
namedtuple_as_object=namedtuple_as_object, namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array, tuple_as_array=tuple_as_array,
iterable_as_array=iterable_as_array, iterable_as_array=iterable_as_array,
bigint_as_string=bigint_as_string,
sort_keys=sort_keys,
item_sort_key=item_sort_key,
for_json=for_json,
ignore_nan=ignore_nan,
int_as_string_bitcount=int_as_string_bitcount,
**kw).iterencode(obj) **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at # could accelerate with writelines in some versions of Python, at
# a debuggability cost # a debuggability cost
...@@ -231,10 +280,10 @@ ...@@ -231,10 +280,10 @@
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None, allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True, encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, namedtuple_as_object=True, tuple_as_array=True,
tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None,
iterable_as_array=False, for_json=False, ignore_nan=False, int_as_string_bitcount=None,
**kw): iterable_as_array=False, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``. """Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types If ``skipkeys`` is false then ``dict`` keys that are not basic types
...@@ -261,9 +310,11 @@ ...@@ -261,9 +310,11 @@
versions of simplejson earlier than 2.1.0, an integer is also accepted versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces. and is converted to a string with that many spaces.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple If specified, ``separators`` should be an
then it will be used instead of the default ``(', ', ': ')`` separators. ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')``
``(',', ':')`` is the most compact JSON representation. if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most
compact JSON representation, you should specify ``(',', ':')`` to eliminate
whitespace.
``encoding`` is the character encoding for str instances, default is UTF-8. ``encoding`` is the character encoding for str instances, default is UTF-8.
...@@ -284,5 +335,30 @@ ...@@ -284,5 +335,30 @@
any object not in the above table that implements ``__iter__()`` any object not in the above table that implements ``__iter__()``
will be encoded as a JSON array. will be encoded as a JSON array.
If *bigint_as_string* is true (not the default), ints 2**53 and higher
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise.
If *int_as_string_bitcount* is a positive number (n), then int of size
greater than or equal to 2**n or lower than or equal to -2**n will be
encoded as strings.
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precendence over
*sort_keys*.
If *sort_keys* is true (default: ``False``), the output of dictionaries
will be sorted by item.
If *for_json* is true (default: ``False``), objects with a ``for_json()``
method will use the return value of that method for encoding as JSON
instead of the object.
If *ignore_nan* is true (default: ``False``), then out of range
:class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as
``null`` in compliance with the ECMA-262 specification. If true, this will
override *allow_nan*.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with ``.default()`` method to serialize additional types), specify it with
...@@ -287,9 +363,10 @@ ...@@ -287,9 +363,10 @@
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with ``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg. the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing
whenever possible.
""" """
# cached encoder # cached encoder
if (not skipkeys and ensure_ascii and if (not skipkeys and ensure_ascii and
check_circular and allow_nan and check_circular and allow_nan and
cls is None and indent is None and separators is None and cls is None and indent is None and separators is None and
...@@ -290,12 +367,16 @@ ...@@ -290,12 +367,16 @@
""" """
# cached encoder # cached encoder
if (not skipkeys and ensure_ascii and if (not skipkeys and ensure_ascii and
check_circular and allow_nan and check_circular and allow_nan and
cls is None and indent is None and separators is None and cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal and encoding == 'utf-8' and default is None and use_decimal
namedtuple_as_object and tuple_as_array and and namedtuple_as_object and tuple_as_array and not iterable_as_array
not iterable_as_array and not kw): and not bigint_as_string and not sort_keys
and not item_sort_key and not for_json
and not ignore_nan and int_as_string_bitcount is None
and not kw
):
return _default_encoder.encode(obj) return _default_encoder.encode(obj)
if cls is None: if cls is None:
cls = JSONEncoder cls = JSONEncoder
...@@ -307,6 +388,12 @@ ...@@ -307,6 +388,12 @@
namedtuple_as_object=namedtuple_as_object, namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array, tuple_as_array=tuple_as_array,
iterable_as_array=iterable_as_array, iterable_as_array=iterable_as_array,
bigint_as_string=bigint_as_string,
sort_keys=sort_keys,
item_sort_key=item_sort_key,
for_json=for_json,
ignore_nan=ignore_nan,
int_as_string_bitcount=int_as_string_bitcount,
**kw).encode(obj) **kw).encode(obj)
...@@ -361,7 +448,8 @@ ...@@ -361,7 +448,8 @@
parse_float=decimal.Decimal for parity with ``dump``. parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead
of subclassing whenever possible.
""" """
return loads(fp.read(), return loads(fp.read(),
...@@ -417,7 +505,8 @@ ...@@ -417,7 +505,8 @@
parse_float=decimal.Decimal for parity with ``dump``. parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead
of subclassing whenever possible.
""" """
if (cls is None and encoding is None and object_hook is None and if (cls is None and encoding is None and object_hook is None and
...@@ -445,9 +534,9 @@ ...@@ -445,9 +534,9 @@
def _toggle_speedups(enabled): def _toggle_speedups(enabled):
import simplejson.decoder as dec from . import decoder as dec
import simplejson.encoder as enc from . import encoder as enc
import simplejson.scanner as scan from . import scanner as scan
c_make_encoder = _import_c_make_encoder() c_make_encoder = _import_c_make_encoder()
if enabled: if enabled:
dec.scanstring = dec.c_scanstring or dec.py_scanstring dec.scanstring = dec.c_scanstring or dec.py_scanstring
...@@ -478,3 +567,9 @@ ...@@ -478,3 +567,9 @@
encoding='utf-8', encoding='utf-8',
default=None, default=None,
) )
def simple_first(kv):
"""Helper function to pass to item_sort_key to sort simple
elements to the top, then container elements.
"""
return (isinstance(kv[1], (list, dict, tuple)), kv[0])
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment