From fddc0183947c5a7182acbefef53c919dd0fec7ae Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 15:34:27 -0400 Subject: [PATCH 01/38] datestamp --- HISTORY.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/HISTORY.rst b/HISTORY.rst index b4cea61..d8dccb1 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -1,8 +1,8 @@ History ------- -0.9.8 -+++++ +0.9.8 (2011-05-22) +++++++++++++++++++ * OpenDocument Spreadsheet support (.ods) * Full Unicode TSV support From 805ccfae3423801721bead9f9a99d802da686828 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 15:39:28 -0400 Subject: [PATCH 02/38] mention formats --- docs/index.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/index.rst b/docs/index.rst index 25ceb85..6cd0233 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -39,6 +39,7 @@ Tablib is an :ref:`MIT Licensed ` format-agnostic tabular dataset library, >>> data.xlsx +Formats supported: XLSX, XLS, ODS, JSON, YAML, CSV, TSV, HTML Table. Testimonials ------------ From b9c74eacc852736d80b7c21a85ea7941b46efdb8 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 15:41:10 -0400 Subject: [PATCH 03/38] lower case --- docs/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 6cd0233..8b4eda5 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -39,7 +39,7 @@ Tablib is an :ref:`MIT Licensed ` format-agnostic tabular dataset library, >>> data.xlsx -Formats supported: XLSX, XLS, ODS, JSON, YAML, CSV, TSV, HTML Table. +Tablib currently supports xlsx, xls, ods, json, yaml, csv, tsv, and html. Testimonials ------------ From 3036bc9e52adfbb47945339226c6a05087ff36f3 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 15:45:34 -0400 Subject: [PATCH 04/38] abandon --- docs/index.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 8b4eda5..25ceb85 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -39,7 +39,6 @@ Tablib is an :ref:`MIT Licensed ` format-agnostic tabular dataset library, >>> data.xlsx -Tablib currently supports xlsx, xls, ods, json, yaml, csv, tsv, and html. Testimonials ------------ From 273d2729ee60a15cc408a55d7165fdcc2fb1b3a1 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 19:36:38 -0400 Subject: [PATCH 05/38] Apache v2 --- LICENSE | 26 ++++++++------------- docs/development.rst | 54 +++++++++++++++++++++++--------------------- docs/index.rst | 2 +- docs/intro.rst | 52 +++++++++++++++++++++--------------------- 4 files changed, 65 insertions(+), 69 deletions(-) diff --git a/LICENSE b/LICENSE index ea8c217..b6bcf64 100644 --- a/LICENSE +++ b/LICENSE @@ -1,19 +1,13 @@ -Copyright (c) 2011 Kenneth Reitz. +Copyright 2011 Kenneth Reitz -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + http://www.apache.org/licenses/LICENSE-2.0 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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. \ No newline at end of file +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/docs/development.rst b/docs/development.rst index 6255d5e..cd6fd13 100644 --- a/docs/development.rst +++ b/docs/development.rst @@ -5,7 +5,8 @@ Development Tablib is under active development, and contributors are welcome. -If you have a feature request, suggestion, or bug report, please open a new issue on GitHub_. To submit patches, please send a pull request on GitHub_. +If you have a feature request, suggestion, or bug report, please open a new +issue on GitHub_. To submit patches, please send a pull request on GitHub_. If you'd like to contribute, there's plenty to do. Here's a short todo list. @@ -42,19 +43,20 @@ Source Control -------------- -Tablib source is controlled with Git_, the lean, mean, distributed source control machine. +Tablib source is controlled with Git_, the lean, mean, distributed source +control machine. The repository is publicly accessable. ``git clone git://github.com/kennethreitz/tablib.git`` - + The project is hosted both on **GitHub** and **git.kennethreitz.com**. - - - GitHub: + + + GitHub: http://github.com/kennethreitz/tablib - "Mirror": - http://git.kennethreitz.com/projects/tablib + "Mirror": + http://git.kennethreitz.com/projects/tablib Git Branch Structure @@ -100,27 +102,27 @@ Tablib features a micro-framework for adding format support. The easiest way to 1. Write a new format interface. :class:`tablib.core` follows a simple pattern for automatically utilizing your format throughout Tablib. Function names are crucial. - + Example **tablib/formats/_xxx.py**: :: title = 'xxx' - + def export_set(dset): .... # returns string representation of given dataset - + def export_book(dbook): .... # returns string representation of given databook - + def import_set(dset, in_stream): ... # populates given Dataset with given datastream - + def import_book(dbook, in_stream): ... # returns Databook instance - + def detect(stream): ... # returns True if given stream is parsable as xxx @@ -130,7 +132,7 @@ Tablib features a micro-framework for adding format support. The easiest way to If the format excludes support for an import/export mechanism (*eg.* :class:`csv ` excludes :class:`Databook ` support), simply don't define the respective functions. Appropriate errors will be raised. -2. +2. Add your new format module to the :class:`tablib.formats.avalable` tuple. @@ -152,7 +154,7 @@ When developing a feature for Tablib, the easiest way to test your changes for p $ ./test_tablib.py -`Hudson CI`_, amongst other tools, supports Java's xUnit testing report format. Nose_ allows us to generate our own xUnit reports. +`Hudson CI`_, amongst other tools, supports Java's xUnit testing report format. Nose_ allows us to generate our own xUnit reports. Installing nose is simple. :: @@ -174,14 +176,14 @@ This will generate a **nosetests.xml** file, which can then be analyzed. Continuous Integration ---------------------- -Every commit made to the **develop** branch is automatically tested and inspected upon receipt with `Hudson CI`_. If you have access to the main repository and broke the build, you will receive an email accordingly. +Every commit made to the **develop** branch is automatically tested and inspected upon receipt with `Hudson CI`_. If you have access to the main repository and broke the build, you will receive an email accordingly. Anyone may view the build status and history at any time. http://ci.kennethreitz.com/ -If you are trustworthy and plan to contribute to tablib on a regular basis, please contact `Kenneth Reitz`_ to get an account on the Hudson Server. +If you are trustworthy and plan to contribute to tablib on a regular basis, please contact `Kenneth Reitz`_ to get an account on the Hudson Server. Additional reports will also be included here in the future, including :pep:`8` checks and stress reports for extremely large datasets. @@ -196,17 +198,17 @@ Additional reports will also be included here in the future, including :pep:`8` Building the Docs ----------------- -Documentation is written in the powerful, flexible, and standard Python documentation format, `reStructured Text`_. +Documentation is written in the powerful, flexible, and standard Python documentation format, `reStructured Text`_. Documentation builds are powered by the powerful Pocoo project, Sphinx_. The :ref:`API Documentation ` is mostly documented inline throughout the module. The Docs live in ``tablib/docs``. In order to build them, you will first need to install Sphinx. :: $ pip install sphinx - + Then, to build an HTML version of the docs, simply run the following from the **docs** directory: :: - $ make html + $ make html Your ``docs/_build/html`` directory will then contain an HTML representation of the documentation, ready for publication on most web servers. @@ -214,10 +216,10 @@ You can also generate the documentation in **ebpub**, **latex**, **json**, *&c* .. admonition:: GitHub Pages - To push the documentation up to `GitHub Pages`_, you will first need to run `sphinx-to-github`_ against your ``docs/_build/html`` directory. - + To push the documentation up to `GitHub Pages`_, you will first need to run `sphinx-to-github`_ against your ``docs/_build/html`` directory. + GitHub Pages are powered by an HTML generation system called Jeckyl_, which is configured to ignore files and folders that begin with "``_``" (*ie.* **_static**). - + @@ -232,8 +234,8 @@ You can also generate the documentation in **ebpub**, **latex**, **json**, *&c* Running it against the docs is even simpler. :: $ sphinx-to-github _build/html - - Move the resulting files to the **gh-pages** branch of your repository, and push it up to GitHub. + + Move the resulting files to the **gh-pages** branch of your repository, and push it up to GitHub. .. _`reStructured Text`: http://docutils.sourceforge.net/rst.html .. _Sphinx: http://sphinx.pocoo.org diff --git a/docs/index.rst b/docs/index.rst index 25ceb85..bd262f3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -22,7 +22,7 @@ Release v\ |version|. (:ref:`Installation `) .. * :ref:`search` -Tablib is an :ref:`MIT Licensed ` format-agnostic tabular dataset library, written in Python. It allows you to import, export, and manipulate tabular data sets. Advanced features include, segregation, dynamic columns, tags & filtering, and seamless format import & export. +Tablib is an :ref:`Apache Licensed ` format-agnostic tabular dataset library, written in Python. It allows you to import, export, and manipulate tabular data sets. Advanced features include, segregation, dynamic columns, tags & filtering, and seamless format import & export. :: diff --git a/docs/intro.rst b/docs/intro.rst index 971afbd..5ac92b8 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -4,7 +4,10 @@ Introduction ============ This part of the documentation covers all the interfaces of Tablib. -Tablib is a format-agnostic tabular dataset library, written in Python. It allows you to Pythonically import, export, and manipulate tabular data sets. Advanced features include, segregation, dynamic columns, tags / filtering, and seamless format import/export. +Tablib is a format-agnostic tabular dataset library, written in Python. +It allows you to Pythonically import, export, and manipulate tabular data sets. +Advanced features include, segregation, dynamic columns, tags / filtering, and +seamless format import/export. Philosphy @@ -21,47 +24,44 @@ Tablib was developed with a few :pep:`20` idioms in mind. All contributions to Tablib should keep these important rules in mind. -.. _mit: +.. _apache: -MIT License ------------ +Apache License v2 +----------------- -A large number of open source projects you find today are `GPL Licensed`_. While the GPL has its time and place, it should most certainly not be your go-to license for your next open source project. +A large number of open source projects you find today are `GPL Licensed`_. +While the GPL has its time and place, it should most certainly not be your +go-to license for your next open source project. -A project that is released as GPL cannot be used in any commercial product without the product itself also being offered as open source. The MIT, BSD, and ISC licenses are great alternatives to the GPL that allow your open-source software to be used in proprietary, closed-source software. +A project that is released as GPL cannot be used in any commercial product +without the product itself also being offered as open source. The MIT, BSD, and +ISC licenses are great alternatives to the GPL that allow your open-source +software to be used in proprietary, closed-source software. -Tablib is released under terms of `The MIT License`_. +Tablib is released under terms of `The Apache License v2`_. .. _`GPL Licensed`: http://www.opensource.org/licenses/gpl-license.php -.. _`The MIT License`: http://www.opensource.org/licenses/mit-license.php +.. _`The Apache License v2`: http://opensource.org/licenses/Apache-2.0 -.. note:: - Tablib will be moved to the `Apache 2 License `_ upon the release of v1.0.0. .. _license: Tablib License -------------- -Copyright (c) 2011 Kenneth Reitz. +Copyright 2011 Kenneth Reitz -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + http://www.apache.org/licenses/LICENSE-2.0 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -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. +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. .. _pythonsupport: From 36fbdda492695e8f7c09d88aa2cde91f7dbaffc6 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 19:43:29 -0400 Subject: [PATCH 06/38] setup.py improvements closes #5 --- setup.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) mode change 100644 => 100755 setup.py diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 index c4f17ac..bd9379e --- a/setup.py +++ b/setup.py @@ -7,12 +7,29 @@ import sys from distutils.core import setup -def publish(): - """Publish to PyPi""" - os.system("python setup.py sdist upload") -if sys.argv[-1] == "publish": - publish() +if sys.argv[-1] == 'publish': + os.system("python setup.py sdist upload") + sys.exit() + +if sys.argv[-1] == 'speedups': + try: + import pip + except ImportError: + print('Pip required.') + sys.exit(1) + + os.system('pip install simplejson pyyaml') + sys.exit() + +if sys.argv[-1] == 'test': + try: + import py + except ImportError: + print('py.test required.') + sys.exit(1) + + os.system('pytest test_tablib.py') sys.exit() required = [] From 5ba56c2bb329c000b1565f7291df860dbb0dcb54 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 19:52:24 -0400 Subject: [PATCH 07/38] Turn off OrderedDict for yaml. Fixes #12. --- tablib/core.py | 21 ++++++++++++++++----- tablib/formats/_yaml.py | 7 ++++--- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/tablib/core.py b/tablib/core.py index 80857ca..c03956f 100644 --- a/tablib/core.py +++ b/tablib/core.py @@ -235,11 +235,16 @@ class Dataset(object): return False - def _package(self, dicts=True): + def _package(self, dicts=True, ordered=True): """Packages Dataset into lists of dictionaries for transmission.""" _data = list(self._data) + if ordered: + dict_pack = OrderedDict + else: + dict_pack = dict + # Execute formatters if self._formatters: for row_i, row in enumerate(_data): @@ -256,7 +261,7 @@ class Dataset(object): if self.headers: if dicts: - data = [OrderedDict(list(zip(self.headers, data_row))) for data_row in _data] + data = [dict_pack(list(zip(self.headers, data_row))) for data_row in _data] else: data = [list(self.headers)] + list(_data) else: @@ -786,13 +791,19 @@ class Databook(object): raise InvalidDatasetType - def _package(self): + def _package(self, ordered=True): """Packages :class:`Databook` for delivery.""" collector = [] + + if ordered: + dict_pack = OrderedDict + else: + dict_pack = dict + for dset in self._datasets: - collector.append(OrderedDict( + collector.append(dict_pack( title = dset.title, - data = dset.dict + data = dset._package(ordered=ordered) )) return collector diff --git a/tablib/formats/_yaml.py b/tablib/formats/_yaml.py index 66800a7..974228b 100644 --- a/tablib/formats/_yaml.py +++ b/tablib/formats/_yaml.py @@ -12,7 +12,7 @@ except ImportError: import tablib.packages.yaml3 as yaml else: import tablib.packages.yaml as yaml - + import tablib @@ -25,7 +25,8 @@ extentions = ('yaml', 'yml') def export_set(dataset): """Returns YAML representation of Dataset.""" - return yaml.dump(dataset.dict) + + return yaml.dump(dataset._package(ordered=False)) def export_book(databook): @@ -50,7 +51,7 @@ def import_book(dbook, in_stream): data.title = sheet['title'] data.dict = sheet['data'] dbook.add_sheet(data) - + def detect(stream): """Returns True if given stream is valid YAML.""" try: From a196b9a5dd5819501ee8958f36483e41b268712f Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 22 May 2011 20:10:14 -0400 Subject: [PATCH 08/38] readme update --- README.rst | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/README.rst b/README.rst index f57ef08..e46228b 100644 --- a/README.rst +++ b/README.rst @@ -28,10 +28,10 @@ Overview -------- `tablib.Dataset()` - A Dataset is a table of tabular data. It may or may not have a header row. They can be build and manipulated as raw Python datatypes (Lists of tuples|dictionaries). Datasets can be imported from JSON, YAML, and CSV; they can be exported to Excel (XLS), JSON, YAML, and CSV. + A Dataset is a table of tabular data. It may or may not have a header row. They can be build and manipulated as raw Python datatypes (Lists of tuples|dictionaries). Datasets can be imported from JSON, YAML, and CSV; they can be exported to XLSX, XLS, ODS, JSON, YAML, CSV, TSV, and HTML. `tablib.Databook()` - A Databook is a set of Datasets. The most common form of a Databook is an Excel file with multiple spreadsheets. Databooks can be imported from JSON and YAML; they can be exported to Excel (XLS), JSON, and YAML. + A Databook is a set of Datasets. The most common form of a Databook is an Excel file with multiple spreadsheets. Databooks can be imported from JSON and YAML; they can be exported to XLSX, XLS, ODS, JSON, and YAML. Usage ----- @@ -141,13 +141,6 @@ changes to the **develop** branch (or branch off of it), and send a pull request. Make sure you add yourself to AUTHORS_. -Roadmap -------- - -v1.0.0: - - Hooks system - - Tablib.ext namespace - - Width detection on XLS out .. _`the repository`: http://github.com/kennethreitz/tablib From 25fe211a22aa15613f778848a050498de5d53b13 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Mon, 23 May 2011 11:20:10 -0400 Subject: [PATCH 09/38] fix setup packages --- setup.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index bd9379e..b2b30b9 100755 --- a/setup.py +++ b/setup.py @@ -47,10 +47,12 @@ setup( author_email='me@kennethreitz.com', url='http://tablib.org', packages= [ - 'tablib', 'tablib.formats', + 'tablib', + 'tablib.formats', 'tablib.packages', 'tablib.packages.xlwt', 'tablib.packages.openpyxl', + 'tablib.packages.odf', 'tablib.packages.openpyxl.shared', 'tablib.packages.openpyxl.reader', 'tablib.packages.openpyxl.writer', From d111cc7cc7d627efdc3939b105404fd23703292d Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Tue, 24 May 2011 17:19:13 -0400 Subject: [PATCH 10/38] testimonial cleanup --- docs/index.rst | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index bd262f3..f45dc64 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -43,13 +43,11 @@ Tablib is an :ref:`Apache Licensed ` format-agnostic tabular dataset lib Testimonials ------------ -`The Library of Congress `_, `National Geographic `_, `Digg, Inc `_, `Northrop Grumman `_, `Discovery Channel `_, -`The Sunlight Foundation `_, and -`NetApp, Inc `_ use Tablib internally. +and `The Sunlight Foundation `_ use Tablib internally. From 42f0a285c33eef9370a87f8bd8c4c71360758025 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Tue, 24 May 2011 18:30:14 -0400 Subject: [PATCH 11/38] gaug.es --- docs/_themes/kr/layout.html | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/_themes/kr/layout.html b/docs/_themes/kr/layout.html index 344ec29..696413a 100644 --- a/docs/_themes/kr/layout.html +++ b/docs/_themes/kr/layout.html @@ -30,4 +30,19 @@ })(); + + + {%- endblock %} From 707164e45946f30f7b194159b7630c10771be0a4 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Wed, 25 May 2011 12:12:04 -0400 Subject: [PATCH 12/38] fixes #17 --- tablib/compat.py | 2 ++ tablib/formats/_json.py | 6 +----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/tablib/compat.py b/tablib/compat.py index 0881369..cb083f9 100644 --- a/tablib/compat.py +++ b/tablib/compat.py @@ -26,6 +26,7 @@ if is_py3: from tablib.packages import markup3 as markup from tablib.packages import openpyxl3 as openpyxl from tablib.packages.odf3 import opendocument, style, text, table + from tablib.packages import anyjson import csv from io import StringIO @@ -45,5 +46,6 @@ else: from tablib.packages.odf import opendocument, style, text, table from tablib.packages import unicodecsv as csv + from tablib.packages import anyjson25 as anyjson unicode = unicode \ No newline at end of file diff --git a/tablib/formats/_json.py b/tablib/formats/_json.py index 8d498df..7e298e1 100644 --- a/tablib/formats/_json.py +++ b/tablib/formats/_json.py @@ -6,11 +6,7 @@ import tablib import sys -if sys.version_info[:2] > (2, 5): - from tablib.packages import anyjson -else: - from tablib.packages import anyjson25 as anyjson - +from tablib.compat import anyjson title = 'json' From f162b19bd6f40e3d4a1723e2a34635386c272beb Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 5 Jun 2011 18:43:08 -0400 Subject: [PATCH 13/38] todo cleanup --- TODO.rst | 2 -- 1 file changed, 2 deletions(-) diff --git a/TODO.rst b/TODO.rst index fc1265a..ecfa974 100644 --- a/TODO.rst +++ b/TODO.rst @@ -3,7 +3,5 @@ - pre/post-import - pre/post-export * Add Tablib.ext namespace -* Fix 2.x/3.x handling (currently internal codebase fork) -* Make CSV write more customizable. * Width detection for XLS output * Documentation Improvements \ No newline at end of file From 1dfcd4223311523e28f6741b7310ec8c6333bc01 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Sun, 5 Jun 2011 18:50:36 -0400 Subject: [PATCH 14/38] whitespace --- test_tablib.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test_tablib.py b/test_tablib.py index 5715eb0..c5210a9 100755 --- a/test_tablib.py +++ b/test_tablib.py @@ -6,13 +6,14 @@ import unittest import sys + + if sys.version_info[0] > 2: from tablib.packages import markup3 as markup else: from tablib.packages import markup - import tablib From 532452632939cbc721780aafa8ea3ec76fd7d18c Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Mon, 20 Jun 2011 12:55:30 -0400 Subject: [PATCH 15/38] remove anyjson --- tablib/compat.py | 2 - tablib/packages/anyjson.py | 117 ---------------------------------- tablib/packages/anyjson25.py | 118 ----------------------------------- 3 files changed, 237 deletions(-) delete mode 100644 tablib/packages/anyjson.py delete mode 100644 tablib/packages/anyjson25.py diff --git a/tablib/compat.py b/tablib/compat.py index cb083f9..0881369 100644 --- a/tablib/compat.py +++ b/tablib/compat.py @@ -26,7 +26,6 @@ if is_py3: from tablib.packages import markup3 as markup from tablib.packages import openpyxl3 as openpyxl from tablib.packages.odf3 import opendocument, style, text, table - from tablib.packages import anyjson import csv from io import StringIO @@ -46,6 +45,5 @@ else: from tablib.packages.odf import opendocument, style, text, table from tablib.packages import unicodecsv as csv - from tablib.packages import anyjson25 as anyjson unicode = unicode \ No newline at end of file diff --git a/tablib/packages/anyjson.py b/tablib/packages/anyjson.py deleted file mode 100644 index a7d1a5f..0000000 --- a/tablib/packages/anyjson.py +++ /dev/null @@ -1,117 +0,0 @@ -""" -Wraps the best available JSON implementation available in a common interface -""" - -__version__ = "0.2.0" -__author__ = "Rune Halvorsen " -__homepage__ = "http://bitbucket.org/runeh/anyjson/" -__docformat__ = "restructuredtext" - -""" - -.. function:: serialize(obj) - - Serialize the object to JSON. - -.. function:: deserialize(str) - - Deserialize JSON-encoded object to a Python object. - -.. function:: force_implementation(name) - - Load a specific json module. This is useful for testing and not much else - -.. attribute:: implementation - - The json implementation object. This is probably not useful to you, - except to get the name of the implementation in use. The name is - available through `implementation.name`. -""" - -import sys - -implementation = None - -""" -.. data:: _modules - - List of known json modules, and the names of their serialize/unserialize - methods, as well as the exception they throw. Exception can be either - an exception class or a string. -""" -_modules = [("cjson", "encode", "EncodeError", "decode", "DecodeError"), - ("jsonlib2", "write", "WriteError", "read", "ReadError"), - ("jsonlib", "write", "WriteError", "read", "ReadError"), - ("simplejson", "dumps", TypeError, "loads", ValueError), - ("json", "dumps", TypeError, "loads", ValueError), - ("django.utils.simplejson", "dumps", TypeError, "loads", - ValueError)] -_fields = ("modname", "encoder", "encerror", "decoder", "decerror") - - -class _JsonImplementation(object): - """Incapsulates a JSON implementation""" - - def __init__(self, modspec): - modinfo = dict(list(zip(_fields, modspec))) - - # No try block. We want importerror to end up at caller - module = self._attempt_load(modinfo["modname"]) - - self.implementation = modinfo["modname"] - self._encode = getattr(module, modinfo["encoder"]) - self._decode = getattr(module, modinfo["decoder"]) - self._encode_error = modinfo["encerror"] - self._decode_error = modinfo["decerror"] - - if isinstance(modinfo["encerror"], str): - self._encode_error = getattr(module, modinfo["encerror"]) - if isinstance(modinfo["decerror"], str): - self._decode_error = getattr(module, modinfo["decerror"]) - - self.name = modinfo["modname"] - - def _attempt_load(self, modname): - """Attempt to load module name modname, returning it on success, - throwing ImportError if module couldn't be imported""" - __import__(modname) - return sys.modules[modname] - - def serialize(self, data): - """Serialize the datastructure to json. Returns a string. Raises - TypeError if the object could not be serialized.""" - try: - return self._encode(data) - except self._encode_error as exc: - raise TypeError(*exc.args) - - def deserialize(self, s): - """deserialize the string to python data types. Raises - ValueError if the string vould not be parsed.""" - try: - return self._decode(s) - except self._decode_error as exc: - raise ValueError(*exc.args) - - -def force_implementation(modname): - """Forces anyjson to use a specific json module if it's available""" - global implementation - for name, spec in [(e[0], e) for e in _modules]: - if name == modname: - implementation = _JsonImplementation(spec) - return - raise ImportError("No module named: %s" % modname) - - -for modspec in _modules: - try: - implementation = _JsonImplementation(modspec) - break - except ImportError: - pass -else: - raise ImportError("No supported JSON module found") - -serialize = lambda value: implementation.serialize(value) -deserialize = lambda value: implementation.deserialize(value) diff --git a/tablib/packages/anyjson25.py b/tablib/packages/anyjson25.py deleted file mode 100644 index ad6fc40..0000000 --- a/tablib/packages/anyjson25.py +++ /dev/null @@ -1,118 +0,0 @@ -u""" -Wraps the best available JSON implementation available in a common interface -""" - -__version__ = u"0.2.0" -__author__ = u"Rune Halvorsen " -__homepage__ = u"http://bitbucket.org/runeh/anyjson/" -__docformat__ = u"restructuredtext" - -u""" - -.. function:: serialize(obj) - - Serialize the object to JSON. - -.. function:: deserialize(str) - - Deserialize JSON-encoded object to a Python object. - -.. function:: force_implementation(name) - - Load a specific json module. This is useful for testing and not much else - -.. attribute:: implementation - - The json implementation object. This is probably not useful to you, - except to get the name of the implementation in use. The name is - available through `implementation.name`. -""" - -import sys -from itertools import izip - -implementation = None - -u""" -.. data:: _modules - - List of known json modules, and the names of their serialize/unserialize - methods, as well as the exception they throw. Exception can be either - an exception class or a string. -""" -_modules = [(u"cjson", u"encode", u"EncodeError", u"decode", u"DecodeError"), - (u"jsonlib2", u"write", u"WriteError", u"read", u"ReadError"), - (u"jsonlib", u"write", u"WriteError", u"read", u"ReadError"), - (u"simplejson", u"dumps", TypeError, u"loads", ValueError), - (u"json", u"dumps", TypeError, u"loads", ValueError), - (u"django.utils.simplejson", u"dumps", TypeError, u"loads", - ValueError)] -_fields = (u"modname", u"encoder", u"encerror", u"decoder", u"decerror") - - -class _JsonImplementation(object): - u"""Incapsulates a JSON implementation""" - - def __init__(self, modspec): - modinfo = dict(list(izip(_fields, modspec))) - - # No try block. We want importerror to end up at caller - module = self._attempt_load(modinfo[u"modname"]) - - self.implementation = modinfo[u"modname"] - self._encode = getattr(module, modinfo[u"encoder"]) - self._decode = getattr(module, modinfo[u"decoder"]) - self._encode_error = modinfo[u"encerror"] - self._decode_error = modinfo[u"decerror"] - - if isinstance(modinfo[u"encerror"], unicode): - self._encode_error = getattr(module, modinfo[u"encerror"]) - if isinstance(modinfo[u"decerror"], unicode): - self._decode_error = getattr(module, modinfo[u"decerror"]) - - self.name = modinfo[u"modname"] - - def _attempt_load(self, modname): - u"""Attempt to load module name modname, returning it on success, - throwing ImportError if module couldn't be imported""" - __import__(modname) - return sys.modules[modname] - - def serialize(self, data): - u"""Serialize the datastructure to json. Returns a string. Raises - TypeError if the object could not be serialized.""" - try: - return self._encode(data) - except self._encode_error, exc: - raise TypeError(*exc.args) - - def deserialize(self, s): - u"""deserialize the string to python data types. Raises - ValueError if the string vould not be parsed.""" - try: - return self._decode(s) - except self._decode_error, exc: - raise ValueError(*exc.args) - - -def force_implementation(modname): - u"""Forces anyjson to use a specific json module if it's available""" - global implementation - for name, spec in [(e[0], e) for e in _modules]: - if name == modname: - implementation = _JsonImplementation(spec) - return - raise ImportError(u"No module named: %s" % modname) - - -for modspec in _modules: - try: - implementation = _JsonImplementation(modspec) - break - except ImportError: - pass -else: - raise ImportError(u"No supported JSON module found") - -serialize = lambda value: implementation.serialize(value) -deserialize = lambda value: implementation.deserialize(value) From 4dab48cd763da70d8ed1294c074843672ecabff3 Mon Sep 17 00:00:00 2001 From: Kenneth Reitz Date: Mon, 20 Jun 2011 12:55:37 -0400 Subject: [PATCH 16/38] add omnijson --- tablib/packages/omnijson/__init__.py | 13 + tablib/packages/omnijson/core.py | 93 ++++ tablib/packages/omnijson/packages/__init__.py | 0 .../omnijson/packages/simplejson/__init__.py | 438 +++++++++++++++ .../omnijson/packages/simplejson/decoder.py | 421 +++++++++++++++ .../omnijson/packages/simplejson/encoder.py | 503 ++++++++++++++++++ .../packages/simplejson/ordered_dict.py | 119 +++++ .../omnijson/packages/simplejson/scanner.py | 70 +++ 8 files changed, 1657 insertions(+) create mode 100644 tablib/packages/omnijson/__init__.py create mode 100644 tablib/packages/omnijson/core.py create mode 100644 tablib/packages/omnijson/packages/__init__.py create mode 100644 tablib/packages/omnijson/packages/simplejson/__init__.py create mode 100644 tablib/packages/omnijson/packages/simplejson/decoder.py create mode 100644 tablib/packages/omnijson/packages/simplejson/encoder.py create mode 100644 tablib/packages/omnijson/packages/simplejson/ordered_dict.py create mode 100644 tablib/packages/omnijson/packages/simplejson/scanner.py diff --git a/tablib/packages/omnijson/__init__.py b/tablib/packages/omnijson/__init__.py new file mode 100644 index 0000000..c10c328 --- /dev/null +++ b/tablib/packages/omnijson/__init__.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import + +from .core import loads, dumps, JSONError + + +__all__ = ('loads', 'dumps', 'JSONError') + + +__version__ = '0.1.2' +__author__ = 'Kenneth Reitz' +__license__ = 'MIT' diff --git a/tablib/packages/omnijson/core.py b/tablib/packages/omnijson/core.py new file mode 100644 index 0000000..8b49537 --- /dev/null +++ b/tablib/packages/omnijson/core.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +""" +omijson.core +~~~~~~~~~~~~ + +This module provides the core omnijson functionality. + +""" + +import sys + +engine = None +_engine = None + + +options = [ + ['ujson', 'loads', 'dumps', (ValueError,)], + ['yajl', 'loads', 'dumps', (TypeError, ValueError)], + ['jsonlib2', 'read', 'write', (ValueError,)], + ['jsonlib', 'read', 'write', (ValueError,)], + ['simplejson', 'loads', 'dumps', (TypeError, ValueError)], + ['json', 'loads', 'dumps', (TypeError, ValueError)], + ['simplejson_from_packages', 'loads', 'dumps', (ValueError,)], +] + + +def _import(engine): + try: + if '_from_' in engine: + engine, package = engine.split('_from_') + m = __import__(package, globals(), locals(), [engine], -1) + return getattr(m, engine) + + return __import__(engine) + + except ImportError: + return False + + +def loads(s, **kwargs): + """Loads JSON object.""" + + try: + return _engine[0](s) + + except: + # crazy 2/3 exception hack + # http://www.voidspace.org.uk/python/weblog/arch_d7_2010_03_20.shtml + + ExceptionClass, why = sys.exc_info()[:2] + + if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]): + raise JSONError(why) + else: + raise why + + +def dumps(o, **kwargs): + """Dumps JSON object.""" + + try: + return _engine[1](o) + + except: + ExceptionClass, why = sys.exc_info()[:2] + + if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]): + raise JSONError(why) + else: + raise why + + +class JSONError(ValueError): + """JSON Failed.""" + + +# ------ +# Magic! +# ------ + + +for e in options: + + __engine = _import(e[0]) + + if __engine: + engine, _engine = e[0], e[1:4] + + for i in (0, 1): + _engine[i] = getattr(__engine, _engine[i]) + + break diff --git a/tablib/packages/omnijson/packages/__init__.py b/tablib/packages/omnijson/packages/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tablib/packages/omnijson/packages/simplejson/__init__.py b/tablib/packages/omnijson/packages/simplejson/__init__.py new file mode 100644 index 0000000..210b957 --- /dev/null +++ b/tablib/packages/omnijson/packages/simplejson/__init__.py @@ -0,0 +1,438 @@ +r"""JSON (JavaScript Object Notation) is a subset of +JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data +interchange format. + +:mod:`simplejson` exposes an API familiar to users of the standard library +:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained +version of the :mod:`json` library contained in Python 2.6, but maintains +compatibility with Python 2.4 and Python 2.5 and (currently) has +significant performance advantages, even without using the optional C +extension for speedups. + +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") + "\"foo\bar" + >>> print json.dumps(u'\u1234') + "\u1234" + >>> print json.dumps('\\') + "\\" + >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) + {"a": 0, "b": 0, "c": 0} + >>> from StringIO import StringIO + >>> io = StringIO() + >>> json.dump(['streaming API'], io) + >>> io.getvalue() + '["streaming API"]' + +Compact encoding:: + + >>> import simplejson as json + >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) + '[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()]) + { + "4": 5, + "6": 7 + } + +Decoding JSON:: + + >>> import simplejson as json + >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] + >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj + True + >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' + True + >>> from StringIO import StringIO + >>> io = StringIO('["streaming API"]') + >>> json.load(io)[0] == 'streaming API' + True + +Specializing JSON object decoding:: + + >>> import simplejson as json + >>> def as_complex(dct): + ... if '__complex__' in dct: + ... return complex(dct['real'], dct['imag']) + ... return dct + ... + >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', + ... object_hook=as_complex) + (1+2j) + >>> from decimal import Decimal + >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') + True + +Specializing JSON object encoding:: + + >>> import simplejson as json + >>> def encode_complex(obj): + ... if isinstance(obj, complex): + ... return [obj.real, obj.imag] + ... raise TypeError(repr(o) + " is not JSON serializable") + ... + >>> json.dumps(2 + 1j, default=encode_complex) + '[2.0, 1.0]' + >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) + '[2.0, 1.0]' + >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) + '[2.0, 1.0]' + + +Using simplejson.tool from the shell to validate and pretty-print:: + + $ echo '{"json":"obj"}' | python -m simplejson.tool + { + "json": "obj" + } + $ echo '{ 1.2:3.4}' | python -m simplejson.tool + Expecting property name: line 1 column 2 (char 2) +""" +__version__ = '2.1.6' +__all__ = [ + 'dump', 'dumps', 'load', 'loads', + 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', + 'OrderedDict', +] + +__author__ = 'Bob Ippolito ' + +from decimal import Decimal + +from decoder import JSONDecoder, JSONDecodeError +from encoder import JSONEncoder +def _import_OrderedDict(): + import collections + try: + return collections.OrderedDict + except AttributeError: + import ordered_dict + return ordered_dict.OrderedDict +OrderedDict = _import_OrderedDict() + +def _import_c_make_encoder(): + try: + from simplejson._speedups import make_encoder + return make_encoder + except ImportError: + return None + +_default_encoder = JSONEncoder( + skipkeys=False, + ensure_ascii=True, + check_circular=True, + allow_nan=True, + indent=None, + separators=None, + encoding='utf-8', + default=None, + use_decimal=False, +) + +def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, + allow_nan=True, cls=None, indent=None, separators=None, + encoding='utf-8', default=None, use_decimal=False, **kw): + """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a + ``.write()``-supporting file-like object). + + If ``skipkeys`` is true then ``dict`` keys that are not basic types + (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) + will be skipped instead of raising a ``TypeError``. + + If ``ensure_ascii`` is false, then the some chunks written to ``fp`` + may be ``unicode`` instances, subject to normal Python ``str`` to + ``unicode`` coercion rules. Unless ``fp.write()`` explicitly + understands ``unicode`` (as in ``codecs.getwriter()``) this is likely + to cause an error. + + If ``check_circular`` is false, then the circular reference check + for container types will be skipped and a circular reference will + result in an ``OverflowError`` (or worse). + + If ``allow_nan`` is false, then it will be a ``ValueError`` to + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) + in strict compliance of the JSON specification, instead of using the + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). + + 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 + representation without any newlines. For backwards compatibility with + versions of simplejson earlier than 2.1.0, an integer is also accepted + and is converted to a string with that many spaces. + + If ``separators`` is an ``(item_separator, dict_separator)`` tuple + then it will be used instead of the default ``(', ', ': ')`` separators. + ``(',', ':')`` is the most compact JSON representation. + + ``encoding`` is the character encoding for str instances, default is UTF-8. + + ``default(obj)`` is a function that should return a serializable version + of obj or raise TypeError. The default simply raises TypeError. + + If *use_decimal* is true (default: ``False``) then decimal.Decimal + will be natively serialized to JSON with full precision. + + To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the + ``.default()`` method to serialize additional types), specify it with + the ``cls`` kwarg. + + """ + # cached encoder + if (not skipkeys and ensure_ascii and + check_circular and allow_nan and + cls is None and indent is None and separators is None and + encoding == 'utf-8' and default is None and not use_decimal + and not kw): + iterable = _default_encoder.iterencode(obj) + else: + if cls is None: + cls = JSONEncoder + iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, + check_circular=check_circular, allow_nan=allow_nan, indent=indent, + separators=separators, encoding=encoding, + default=default, use_decimal=use_decimal, **kw).iterencode(obj) + # could accelerate with writelines in some versions of Python, at + # a debuggability cost + for chunk in iterable: + fp.write(chunk) + + +def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, + allow_nan=True, cls=None, indent=None, separators=None, + encoding='utf-8', default=None, use_decimal=False, **kw): + """Serialize ``obj`` to a JSON formatted ``str``. + + If ``skipkeys`` is false then ``dict`` keys that are not basic types + (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) + will be skipped instead of raising a ``TypeError``. + + If ``ensure_ascii`` is false, then the return value will be a + ``unicode`` instance subject to normal Python ``str`` to ``unicode`` + coercion rules instead of being escaped to an ASCII ``str``. + + If ``check_circular`` is false, then the circular reference check + for container types will be skipped and a circular reference will + result in an ``OverflowError`` (or worse). + + If ``allow_nan`` is false, then it will be a ``ValueError`` to + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in + strict compliance of the JSON specification, instead of using the + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). + + 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 + representation without any newlines. For backwards compatibility with + versions of simplejson earlier than 2.1.0, an integer is also accepted + and is converted to a string with that many spaces. + + If ``separators`` is an ``(item_separator, dict_separator)`` tuple + then it will be used instead of the default ``(', ', ': ')`` separators. + ``(',', ':')`` is the most compact JSON representation. + + ``encoding`` is the character encoding for str instances, default is UTF-8. + + ``default(obj)`` is a function that should return a serializable version + of obj or raise TypeError. The default simply raises TypeError. + + If *use_decimal* is true (default: ``False``) then decimal.Decimal + will be natively serialized to JSON with full precision. + + To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the + ``.default()`` method to serialize additional types), specify it with + the ``cls`` kwarg. + + """ + # cached encoder + if (not skipkeys and ensure_ascii and + check_circular and allow_nan and + cls is None and indent is None and separators is None and + encoding == 'utf-8' and default is None and not use_decimal + and not kw): + return _default_encoder.encode(obj) + if cls is None: + cls = JSONEncoder + return cls( + skipkeys=skipkeys, ensure_ascii=ensure_ascii, + check_circular=check_circular, allow_nan=allow_nan, indent=indent, + separators=separators, encoding=encoding, default=default, + use_decimal=use_decimal, **kw).encode(obj) + + +_default_decoder = JSONDecoder(encoding=None, object_hook=None, + object_pairs_hook=None) + + +def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, + parse_int=None, parse_constant=None, object_pairs_hook=None, + use_decimal=False, **kw): + """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing + a JSON document) to a Python object. + + *encoding* determines the encoding used to interpret any + :class:`str` objects decoded by this instance (``'utf-8'`` by + default). It has no effect when decoding :class:`unicode` objects. + + Note that currently only encodings that are a superset of ASCII work, + strings of other encodings should be passed in as :class:`unicode`. + + *object_hook*, if specified, will be called with the result of every + JSON object decoded and its return value will be used in place of the + given :class:`dict`. This can be used to provide custom + deserializations (e.g. to support JSON-RPC class hinting). + + *object_pairs_hook* is an optional function that will be called with + the result of any object literal decode with an ordered list of pairs. + The return value of *object_pairs_hook* will be used instead of the + :class:`dict`. This feature can be used to implement custom decoders + that rely on the order that the key and value pairs are decoded (for + example, :func:`collections.OrderedDict` will remember the order of + insertion). If *object_hook* is also defined, the *object_pairs_hook* + takes priority. + + *parse_float*, if specified, will be called with the string of every + JSON float to be decoded. By default, this is equivalent to + ``float(num_str)``. This can be used to use another datatype or parser + for JSON floats (e.g. :class:`decimal.Decimal`). + + *parse_int*, if specified, will be called with the string of every + JSON int to be decoded. By default, this is equivalent to + ``int(num_str)``. This can be used to use another datatype or parser + for JSON integers (e.g. :class:`float`). + + *parse_constant*, if specified, will be called with one of the + following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This + can be used to raise an exception if invalid JSON numbers are + encountered. + + If *use_decimal* is true (default: ``False``) then it implies + parse_float=decimal.Decimal for parity with ``dump``. + + To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` + kwarg. + + """ + return loads(fp.read(), + encoding=encoding, cls=cls, object_hook=object_hook, + parse_float=parse_float, parse_int=parse_int, + parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, + use_decimal=use_decimal, **kw) + + +def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, + parse_int=None, parse_constant=None, object_pairs_hook=None, + use_decimal=False, **kw): + """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON + document) to a Python object. + + *encoding* determines the encoding used to interpret any + :class:`str` objects decoded by this instance (``'utf-8'`` by + default). It has no effect when decoding :class:`unicode` objects. + + Note that currently only encodings that are a superset of ASCII work, + strings of other encodings should be passed in as :class:`unicode`. + + *object_hook*, if specified, will be called with the result of every + JSON object decoded and its return value will be used in place of the + given :class:`dict`. This can be used to provide custom + deserializations (e.g. to support JSON-RPC class hinting). + + *object_pairs_hook* is an optional function that will be called with + the result of any object literal decode with an ordered list of pairs. + The return value of *object_pairs_hook* will be used instead of the + :class:`dict`. This feature can be used to implement custom decoders + that rely on the order that the key and value pairs are decoded (for + example, :func:`collections.OrderedDict` will remember the order of + insertion). If *object_hook* is also defined, the *object_pairs_hook* + takes priority. + + *parse_float*, if specified, will be called with the string of every + JSON float to be decoded. By default, this is equivalent to + ``float(num_str)``. This can be used to use another datatype or parser + for JSON floats (e.g. :class:`decimal.Decimal`). + + *parse_int*, if specified, will be called with the string of every + JSON int to be decoded. By default, this is equivalent to + ``int(num_str)``. This can be used to use another datatype or parser + for JSON integers (e.g. :class:`float`). + + *parse_constant*, if specified, will be called with one of the + following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This + can be used to raise an exception if invalid JSON numbers are + encountered. + + If *use_decimal* is true (default: ``False``) then it implies + parse_float=decimal.Decimal for parity with ``dump``. + + To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` + kwarg. + + """ + if (cls is None and encoding is None and object_hook is None and + parse_int is None and parse_float is None and + parse_constant is None and object_pairs_hook is None + and not use_decimal and not kw): + return _default_decoder.decode(s) + if cls is None: + cls = JSONDecoder + if object_hook is not None: + kw['object_hook'] = object_hook + if object_pairs_hook is not None: + kw['object_pairs_hook'] = object_pairs_hook + if parse_float is not None: + kw['parse_float'] = parse_float + if parse_int is not None: + kw['parse_int'] = parse_int + if parse_constant is not None: + kw['parse_constant'] = parse_constant + if use_decimal: + if parse_float is not None: + raise TypeError("use_decimal=True implies parse_float=Decimal") + kw['parse_float'] = Decimal + return cls(encoding=encoding, **kw).decode(s) + + +def _toggle_speedups(enabled): + import simplejson.decoder as dec + import simplejson.encoder as enc + import simplejson.scanner as scan + c_make_encoder = _import_c_make_encoder() + if enabled: + dec.scanstring = dec.c_scanstring or dec.py_scanstring + enc.c_make_encoder = c_make_encoder + enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or + enc.py_encode_basestring_ascii) + scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner + else: + dec.scanstring = dec.py_scanstring + enc.c_make_encoder = None + enc.encode_basestring_ascii = enc.py_encode_basestring_ascii + scan.make_scanner = scan.py_make_scanner + dec.make_scanner = scan.make_scanner + global _default_decoder + _default_decoder = JSONDecoder( + encoding=None, + object_hook=None, + object_pairs_hook=None, + ) + global _default_encoder + _default_encoder = JSONEncoder( + skipkeys=False, + ensure_ascii=True, + check_circular=True, + allow_nan=True, + indent=None, + separators=None, + encoding='utf-8', + default=None, + ) diff --git a/tablib/packages/omnijson/packages/simplejson/decoder.py b/tablib/packages/omnijson/packages/simplejson/decoder.py new file mode 100644 index 0000000..3e36e56 --- /dev/null +++ b/tablib/packages/omnijson/packages/simplejson/decoder.py @@ -0,0 +1,421 @@ +"""Implementation of JSONDecoder +""" +import re +import sys +import struct + +from .scanner import make_scanner +def _import_c_scanstring(): + try: + from simplejson._speedups import scanstring + return scanstring + except ImportError: + return None +c_scanstring = _import_c_scanstring() + +__all__ = ['JSONDecoder'] + +FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL + +def _floatconstants(): + _BYTES = '7FF80000000000007FF0000000000000'.decode('hex') + # The struct module in Python 2.4 would get frexp() out of range here + # when an endian is specified in the format string. Fixed in Python 2.5+ + if sys.byteorder != 'big': + _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] + nan, inf = struct.unpack('dd', _BYTES) + return nan, inf, -inf + +NaN, PosInf, NegInf = _floatconstants() + + +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) + + """ + 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 + else: + colno = pos - doc.rindex('\n', 0, pos) + return lineno, colno + + +def errmsg(msg, doc, pos, end=None): + # Note that this function is called from _speedups + lineno, colno = linecol(doc, pos) + if end is None: + #fmt = '{0}: line {1} column {2} (char {3})' + #return fmt.format(msg, lineno, colno, pos) + fmt = '%s: line %d column %d (char %d)' + return fmt % (msg, lineno, colno, pos) + endlineno, endcolno = linecol(doc, end) + #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})' + #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end) + fmt = '%s: line %d column %d - line %d column %d (char %d - %d)' + return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end) + + +_CONSTANTS = { + '-Infinity': NegInf, + 'Infinity': PosInf, + 'NaN': NaN, +} + +STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) +BACKSLASH = { + '"': u'"', '\\': u'\\', '/': u'/', + 'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t', +} + +DEFAULT_ENCODING = "utf-8" + +def py_scanstring(s, end, encoding=None, strict=True, + _b=BACKSLASH, _m=STRINGCHUNK.match): + """Scan the string s for a JSON string. End is the index of the + character in s after the quote that started the JSON string. + Unescapes all valid JSON string escape sequences and raises ValueError + on attempt to decode an invalid string. If strict is False then literal + control characters are allowed in the string. + + Returns a tuple of the decoded string and the index of the character in s + after the end quote.""" + if encoding is None: + encoding = DEFAULT_ENCODING + chunks = [] + _append = chunks.append + begin = end - 1 + while 1: + chunk = _m(s, end) + if chunk is None: + raise JSONDecodeError( + "Unterminated string starting at", s, begin) + end = chunk.end() + content, terminator = chunk.groups() + # Content is contains zero or more unescaped string characters + if content: + if not isinstance(content, unicode): + content = unicode(content, encoding) + _append(content) + # Terminator is the end of string, a literal control character, + # or a backslash denoting that an escape sequence follows + if terminator == '"': + break + elif terminator != '\\': + if strict: + msg = "Invalid control character %r at" % (terminator,) + #msg = "Invalid control character {0!r} at".format(terminator) + raise JSONDecodeError(msg, s, end) + else: + _append(terminator) + continue + try: + esc = s[end] + except IndexError: + raise JSONDecodeError( + "Unterminated string starting at", s, begin) + # If not a unicode escape sequence, must be in the lookup table + if esc != 'u': + try: + char = _b[esc] + except KeyError: + msg = "Invalid \\escape: " + repr(esc) + raise JSONDecodeError(msg, s, end) + end += 1 + else: + # Unicode escape sequence + esc = s[end + 1:end + 5] + next_end = end + 5 + if len(esc) != 4: + msg = "Invalid \\uXXXX escape" + raise JSONDecodeError(msg, s, end) + uni = int(esc, 16) + # Check for surrogate pair on UCS-4 systems + if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: + msg = "Invalid \\uXXXX\\uXXXX surrogate pair" + if not s[end + 5:end + 7] == '\\u': + raise JSONDecodeError(msg, s, end) + esc2 = s[end + 7:end + 11] + if len(esc2) != 4: + raise JSONDecodeError(msg, s, end) + uni2 = int(esc2, 16) + uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) + next_end += 6 + char = unichr(uni) + end = next_end + # Append the unescaped character + _append(char) + return u''.join(chunks), end + + +# Use speedup if available +scanstring = c_scanstring or py_scanstring + +WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) +WHITESPACE_STR = ' \t\n\r' + +def JSONObject((s, end), encoding, strict, scan_once, object_hook, + object_pairs_hook, memo=None, + _w=WHITESPACE.match, _ws=WHITESPACE_STR): + # Backwards compatibility + if memo is None: + memo = {} + memo_get = memo.setdefault + pairs = [] + # Use a slice to prevent IndexError from being raised, the following + # check will raise a more specific ValueError if the string is empty + nextchar = s[end:end + 1] + # Normally we expect nextchar == '"' + if nextchar != '"': + if nextchar in _ws: + end = _w(s, end).end() + nextchar = s[end:end + 1] + # Trivial empty object + if nextchar == '}': + if object_pairs_hook is not None: + result = object_pairs_hook(pairs) + return result, end + 1 + pairs = {} + if object_hook is not None: + pairs = object_hook(pairs) + return pairs, end + 1 + elif nextchar != '"': + raise JSONDecodeError("Expecting property name", s, end) + end += 1 + while True: + key, end = scanstring(s, end, encoding, strict) + key = memo_get(key, key) + + # To skip some function call overhead we optimize the fast paths where + # the JSON key separator is ": " or just ":". + if s[end:end + 1] != ':': + end = _w(s, end).end() + if s[end:end + 1] != ':': + raise JSONDecodeError("Expecting : delimiter", s, end) + + end += 1 + + try: + if s[end] in _ws: + end += 1 + if s[end] in _ws: + end = _w(s, end + 1).end() + except IndexError: + pass + + try: + value, end = scan_once(s, end) + except StopIteration: + raise JSONDecodeError("Expecting object", s, end) + pairs.append((key, value)) + + try: + nextchar = s[end] + if nextchar in _ws: + end = _w(s, end + 1).end() + nextchar = s[end] + except IndexError: + nextchar = '' + end += 1 + + if nextchar == '}': + break + elif nextchar != ',': + raise JSONDecodeError("Expecting , delimiter", s, end - 1) + + try: + nextchar = s[end] + if nextchar in _ws: + end += 1 + nextchar = s[end] + if nextchar in _ws: + end = _w(s, end + 1).end() + nextchar = s[end] + except IndexError: + nextchar = '' + + end += 1 + if nextchar != '"': + raise JSONDecodeError("Expecting property name", s, end - 1) + + if object_pairs_hook is not None: + result = object_pairs_hook(pairs) + return result, end + pairs = dict(pairs) + if object_hook is not None: + pairs = object_hook(pairs) + return pairs, end + +def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR): + values = [] + nextchar = s[end:end + 1] + if nextchar in _ws: + end = _w(s, end + 1).end() + nextchar = s[end:end + 1] + # Look-ahead for trivial empty array + if nextchar == ']': + return values, end + 1 + _append = values.append + while True: + try: + value, end = scan_once(s, end) + except StopIteration: + raise JSONDecodeError("Expecting object", s, end) + _append(value) + nextchar = s[end:end + 1] + if nextchar in _ws: + end = _w(s, end + 1).end() + nextchar = s[end:end + 1] + end += 1 + if nextchar == ']': + break + elif nextchar != ',': + raise JSONDecodeError("Expecting , delimiter", s, end) + + try: + if s[end] in _ws: + end += 1 + if s[end] in _ws: + end = _w(s, end + 1).end() + except IndexError: + pass + + return values, end + +class JSONDecoder(object): + """Simple JSON decoder + + Performs the following translations in decoding by default: + + +---------------+-------------------+ + | JSON | Python | + +===============+===================+ + | object | dict | + +---------------+-------------------+ + | array | list | + +---------------+-------------------+ + | string | unicode | + +---------------+-------------------+ + | number (int) | int, long | + +---------------+-------------------+ + | number (real) | float | + +---------------+-------------------+ + | true | True | + +---------------+-------------------+ + | false | False | + +---------------+-------------------+ + | null | None | + +---------------+-------------------+ + + It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as + their corresponding ``float`` values, which is outside the JSON spec. + + """ + + def __init__(self, encoding=None, object_hook=None, parse_float=None, + parse_int=None, parse_constant=None, strict=True, + object_pairs_hook=None): + """ + *encoding* determines the encoding used to interpret any + :class:`str` objects decoded by this instance (``'utf-8'`` by + default). It has no effect when decoding :class:`unicode` objects. + + Note that currently only encodings that are a superset of ASCII work, + strings of other encodings should be passed in as :class:`unicode`. + + *object_hook*, if specified, will be called with the result of every + JSON object decoded and its return value will be used in place of the + given :class:`dict`. This can be used to provide custom + deserializations (e.g. to support JSON-RPC class hinting). + + *object_pairs_hook* is an optional function that will be called with + the result of any object literal decode with an ordered list of pairs. + The return value of *object_pairs_hook* will be used instead of the + :class:`dict`. This feature can be used to implement custom decoders + that rely on the order that the key and value pairs are decoded (for + example, :func:`collections.OrderedDict` will remember the order of + insertion). If *object_hook* is also defined, the *object_pairs_hook* + takes priority. + + *parse_float*, if specified, will be called with the string of every + JSON float to be decoded. By default, this is equivalent to + ``float(num_str)``. This can be used to use another datatype or parser + for JSON floats (e.g. :class:`decimal.Decimal`). + + *parse_int*, if specified, will be called with the string of every + JSON int to be decoded. By default, this is equivalent to + ``int(num_str)``. This can be used to use another datatype or parser + for JSON integers (e.g. :class:`float`). + + *parse_constant*, if specified, will be called with one of the + following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This + can be used to raise an exception if invalid JSON numbers are + encountered. + + *strict* controls the parser's behavior when it encounters an + invalid control character in a string. The default setting of + ``True`` means that unescaped control characters are parse errors, if + ``False`` then control characters will be allowed in strings. + + """ + self.encoding = encoding + self.object_hook = object_hook + self.object_pairs_hook = object_pairs_hook + self.parse_float = parse_float or float + self.parse_int = parse_int or int + self.parse_constant = parse_constant or _CONSTANTS.__getitem__ + self.strict = strict + self.parse_object = JSONObject + self.parse_array = JSONArray + self.parse_string = scanstring + self.memo = {} + self.scan_once = make_scanner(self) + + def decode(self, s, _w=WHITESPACE.match): + """Return the Python representation of ``s`` (a ``str`` or ``unicode`` + instance containing a JSON document) + + """ + obj, end = self.raw_decode(s, idx=_w(s, 0).end()) + end = _w(s, end).end() + if end != len(s): + raise JSONDecodeError("Extra data", s, end, len(s)) + return obj + + def raw_decode(self, s, idx=0): + """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` + beginning with a JSON document) and return a 2-tuple of the Python + representation and the index in ``s`` where the document ended. + + This can be used to decode a JSON document from a string that may + have extraneous data at the end. + + """ + try: + obj, end = self.scan_once(s, idx) + except StopIteration: + raise JSONDecodeError("No JSON object could be decoded", s, idx) + return obj, end diff --git a/tablib/packages/omnijson/packages/simplejson/encoder.py b/tablib/packages/omnijson/packages/simplejson/encoder.py new file mode 100644 index 0000000..f1269f3 --- /dev/null +++ b/tablib/packages/omnijson/packages/simplejson/encoder.py @@ -0,0 +1,503 @@ +"""Implementation of JSONEncoder +""" +import re +from decimal import Decimal + +def _import_speedups(): + try: + from simplejson import _speedups + return _speedups.encode_basestring_ascii, _speedups.make_encoder + except ImportError: + return None, None +c_encode_basestring_ascii, c_make_encoder = _import_speedups() + +from .decoder import PosInf + +ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') +ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') +HAS_UTF8 = re.compile(r'[\x80-\xff]') +ESCAPE_DCT = { + '\\': '\\\\', + '"': '\\"', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', +} +for i in range(0x20): + #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) + ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) + +FLOAT_REPR = repr + +def encode_basestring(s): + """Return a JSON representation of a Python string + + """ + if isinstance(s, str) and HAS_UTF8.search(s) is not None: + s = s.decode('utf-8') + def replace(match): + return ESCAPE_DCT[match.group(0)] + return u'"' + ESCAPE.sub(replace, s) + u'"' + + +def py_encode_basestring_ascii(s): + """Return an ASCII-only JSON representation of a Python string + + """ + if isinstance(s, str) and HAS_UTF8.search(s) is not None: + s = s.decode('utf-8') + def replace(match): + s = match.group(0) + try: + return ESCAPE_DCT[s] + except KeyError: + n = ord(s) + if n < 0x10000: + #return '\\u{0:04x}'.format(n) + return '\\u%04x' % (n,) + else: + # surrogate pair + n -= 0x10000 + s1 = 0xd800 | ((n >> 10) & 0x3ff) + s2 = 0xdc00 | (n & 0x3ff) + #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) + return '\\u%04x\\u%04x' % (s1, s2) + return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' + + +encode_basestring_ascii = ( + c_encode_basestring_ascii or py_encode_basestring_ascii) + +class JSONEncoder(object): + """Extensible JSON encoder for Python data structures. + + Supports the following objects and types by default: + + +-------------------+---------------+ + | Python | JSON | + +===================+===============+ + | dict | object | + +-------------------+---------------+ + | list, tuple | array | + +-------------------+---------------+ + | str, unicode | string | + +-------------------+---------------+ + | int, long, float | number | + +-------------------+---------------+ + | True | true | + +-------------------+---------------+ + | False | false | + +-------------------+---------------+ + | None | null | + +-------------------+---------------+ + + To extend this to recognize other objects, subclass and implement a + ``.default()`` method with another method that returns a serializable + object for ``o`` if possible, otherwise it should call the superclass + implementation (to raise ``TypeError``). + + """ + item_separator = ', ' + key_separator = ': ' + def __init__(self, skipkeys=False, ensure_ascii=True, + check_circular=True, allow_nan=True, sort_keys=False, + indent=None, separators=None, encoding='utf-8', default=None, + use_decimal=False): + """Constructor for JSONEncoder, with sensible defaults. + + If skipkeys is false, then it is a TypeError to attempt + encoding of keys that are not str, int, long, float or None. If + skipkeys is True, such items are simply skipped. + + If ensure_ascii is true, the output is guaranteed to be str + objects with all incoming unicode characters escaped. If + ensure_ascii is false, the output will be unicode object. + + If check_circular is true, then lists, dicts, and custom encoded + objects will be checked for circular references during encoding to + prevent an infinite recursion (which would cause an OverflowError). + Otherwise, no such check takes place. + + If allow_nan is true, then NaN, Infinity, and -Infinity will be + encoded as such. This behavior is not JSON specification compliant, + but is consistent with most JavaScript based encoders and decoders. + Otherwise, it will be a ValueError to encode such floats. + + If sort_keys is true, then the output of dictionaries 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. + + 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 + representation without any newlines. For backwards compatibility with + versions of simplejson earlier than 2.1.0, an integer is also accepted + and is converted to a string with that many spaces. + + If specified, separators should be a (item_separator, key_separator) + tuple. The default is (', ', ': '). To get the most compact JSON + representation you should specify (',', ':') to eliminate whitespace. + + If specified, default is a function that gets called for objects + that can't otherwise be serialized. It should return a JSON encodable + version of the object or raise a ``TypeError``. + + If encoding is not None, then all input strings will be + transformed into unicode using that encoding prior to JSON-encoding. + The default is UTF-8. + + If use_decimal is true (not the default), ``decimal.Decimal`` will + be supported directly by the encoder. For the inverse, decode JSON + with ``parse_float=decimal.Decimal``. + + """ + + self.skipkeys = skipkeys + self.ensure_ascii = ensure_ascii + self.check_circular = check_circular + self.allow_nan = allow_nan + self.sort_keys = sort_keys + self.use_decimal = use_decimal + if isinstance(indent, (int, long)): + indent = ' ' * indent + self.indent = indent + if separators is not None: + self.item_separator, self.key_separator = separators + elif indent is not None: + self.item_separator = ',' + if default is not None: + self.default = default + self.encoding = encoding + + def default(self, o): + """Implement this method in a subclass such that it returns + a serializable object for ``o``, or calls the base implementation + (to raise a ``TypeError``). + + For example, to support arbitrary iterators, you could + implement default like this:: + + def default(self, o): + try: + iterable = iter(o) + except TypeError: + pass + else: + return list(iterable) + return JSONEncoder.default(self, o) + + """ + raise TypeError(repr(o) + " is not JSON serializable") + + def encode(self, o): + """Return a JSON string representation of a Python data structure. + + >>> from simplejson import JSONEncoder + >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) + '{"foo": ["bar", "baz"]}' + + """ + # This is for extremely simple cases and benchmarks. + if isinstance(o, basestring): + if isinstance(o, str): + _encoding = self.encoding + if (_encoding is not None + and not (_encoding == 'utf-8')): + o = o.decode(_encoding) + if self.ensure_ascii: + return encode_basestring_ascii(o) + else: + return encode_basestring(o) + # This doesn't pass the iterator directly to ''.join() because the + # exceptions aren't as detailed. The list call should be roughly + # equivalent to the PySequence_Fast that ''.join() would do. + chunks = self.iterencode(o, _one_shot=True) + if not isinstance(chunks, (list, tuple)): + chunks = list(chunks) + if self.ensure_ascii: + return ''.join(chunks) + else: + return u''.join(chunks) + + def iterencode(self, o, _one_shot=False): + """Encode the given object and yield each string + representation as available. + + For example:: + + for chunk in JSONEncoder().iterencode(bigobject): + mysocket.write(chunk) + + """ + if self.check_circular: + markers = {} + else: + markers = None + if self.ensure_ascii: + _encoder = encode_basestring_ascii + else: + _encoder = encode_basestring + if self.encoding != 'utf-8': + def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): + if isinstance(o, str): + o = o.decode(_encoding) + return _orig_encoder(o) + + def floatstr(o, allow_nan=self.allow_nan, + _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): + # Check for specials. Note that this type of test is processor + # and/or platform-specific, so do tests which don't depend on + # the internals. + + if o != o: + text = 'NaN' + elif o == _inf: + text = 'Infinity' + elif o == _neginf: + text = '-Infinity' + else: + return _repr(o) + + if not allow_nan: + raise ValueError( + "Out of range float values are not JSON compliant: " + + repr(o)) + + return text + + + key_memo = {} + if (_one_shot and c_make_encoder is not None + and self.indent is None): + _iterencode = c_make_encoder( + markers, self.default, _encoder, self.indent, + self.key_separator, self.item_separator, self.sort_keys, + self.skipkeys, self.allow_nan, key_memo, self.use_decimal) + else: + _iterencode = _make_iterencode( + markers, self.default, _encoder, self.indent, floatstr, + self.key_separator, self.item_separator, self.sort_keys, + self.skipkeys, _one_shot, self.use_decimal) + try: + return _iterencode(o, 0) + finally: + key_memo.clear() + + +class JSONEncoderForHTML(JSONEncoder): + """An encoder that produces JSON safe to embed in HTML. + + To embed JSON content in, say, a script tag on a web page, the + characters &, < and > should be escaped. They cannot be escaped + with the usual entities (e.g. &) because they are not expanded + within