├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── README.rst ├── docs └── index.html ├── history.md ├── hjson ├── __init__.py ├── compat.py ├── decoder.py ├── encoder.py ├── encoderH.py ├── ordered_dict.py ├── scanner.py ├── tests │ ├── __init__.py │ ├── assets │ │ ├── charset2_result.hjson │ │ ├── charset2_result.json │ │ ├── charset2_test.hjson │ │ ├── charset_result.hjson │ │ ├── charset_result.json │ │ ├── charset_test.hjson │ │ ├── comments_result.hjson │ │ ├── comments_result.json │ │ ├── comments_test.hjson │ │ ├── empty_result.hjson │ │ ├── empty_result.json │ │ ├── empty_test.hjson │ │ ├── extra │ │ │ ├── notabs_result.hjson │ │ │ ├── notabs_result.json │ │ │ ├── notabs_test.json │ │ │ ├── notabs_testmeta.hjson │ │ │ ├── root_result.hjson │ │ │ ├── root_result.json │ │ │ ├── root_test.hjson │ │ │ ├── root_testmeta.hjson │ │ │ ├── separator_result.hjson │ │ │ ├── separator_result.json │ │ │ ├── separator_test.json │ │ │ └── separator_testmeta.hjson │ │ ├── failCharset1_test.hjson │ │ ├── failJSON02_test.json │ │ ├── failJSON05_test.json │ │ ├── failJSON06_test.json │ │ ├── failJSON07_test.json │ │ ├── failJSON08_test.json │ │ ├── failJSON10_test.json │ │ ├── failJSON11_test.json │ │ ├── failJSON12_test.json │ │ ├── failJSON13_test.json │ │ ├── failJSON14_test.json │ │ ├── failJSON15_test.json │ │ ├── failJSON16_test.json │ │ ├── failJSON17_test.json │ │ ├── failJSON19_test.json │ │ ├── failJSON20_test.json │ │ ├── failJSON21_test.json │ │ ├── failJSON22_test.json │ │ ├── failJSON23_test.json │ │ ├── failJSON26_test.json │ │ ├── failJSON28_test.json │ │ ├── failJSON29_test.json │ │ ├── failJSON30_test.json │ │ ├── failJSON31_test.json │ │ ├── failJSON32_test.json │ │ ├── failJSON33_test.json │ │ ├── failJSON34_test.json │ │ ├── failKey1_test.hjson │ │ ├── failKey2_test.hjson │ │ ├── failKey3_test.hjson │ │ ├── failKey4_test.hjson │ │ ├── failKey5_test.hjson │ │ ├── failMLStr1_test.hjson │ │ ├── failObj1_test.hjson │ │ ├── failObj2_test.hjson │ │ ├── failObj3_test.hjson │ │ ├── failStr1a_test.hjson │ │ ├── failStr1b_test.hjson │ │ ├── failStr1c_test.hjson │ │ ├── failStr1d_test.hjson │ │ ├── failStr2a_test.hjson │ │ ├── failStr2b_test.hjson │ │ ├── failStr2c_test.hjson │ │ ├── failStr2d_test.hjson │ │ ├── failStr3a_test.hjson │ │ ├── failStr3b_test.hjson │ │ ├── failStr3c_test.hjson │ │ ├── failStr3d_test.hjson │ │ ├── failStr4a_test.hjson │ │ ├── failStr4b_test.hjson │ │ ├── failStr4c_test.hjson │ │ ├── failStr4d_test.hjson │ │ ├── failStr5a_test.hjson │ │ ├── failStr5b_test.hjson │ │ ├── failStr5c_test.hjson │ │ ├── failStr5d_test.hjson │ │ ├── failStr6a_test.hjson │ │ ├── failStr6b_test.hjson │ │ ├── failStr6c_test.hjson │ │ ├── failStr6d_test.hjson │ │ ├── failStr7a_test.hjson │ │ ├── failStr8a_test.hjson │ │ ├── kan_result.hjson │ │ ├── kan_result.json │ │ ├── kan_test.hjson │ │ ├── keys_result.hjson │ │ ├── keys_result.json │ │ ├── keys_test.hjson │ │ ├── mltabs_result.hjson │ │ ├── mltabs_result.json │ │ ├── mltabs_test.json │ │ ├── oa_result.hjson │ │ ├── oa_result.json │ │ ├── oa_test.hjson │ │ ├── pass1_result.hjson │ │ ├── pass1_result.json │ │ ├── pass1_test.json │ │ ├── pass2_result.hjson │ │ ├── pass2_result.json │ │ ├── pass2_test.json │ │ ├── pass3_result.hjson │ │ ├── pass3_result.json │ │ ├── pass3_test.json │ │ ├── pass4_result.hjson │ │ ├── pass4_result.json │ │ ├── pass4_test.json │ │ ├── passSingle_result.hjson │ │ ├── passSingle_result.json │ │ ├── passSingle_test.hjson │ │ ├── stringify │ │ │ ├── quotes_all_result.hjson │ │ │ ├── quotes_all_result.json │ │ │ ├── quotes_all_test.hjson │ │ │ ├── quotes_all_testmeta.hjson │ │ │ ├── quotes_always_result.hjson │ │ │ ├── quotes_always_result.json │ │ │ ├── quotes_always_test.hjson │ │ │ ├── quotes_always_testmeta.hjson │ │ │ ├── quotes_keys_result.hjson │ │ │ ├── quotes_keys_result.json │ │ │ ├── quotes_keys_test.hjson │ │ │ ├── quotes_keys_testmeta.hjson │ │ │ ├── quotes_strings_ml_result.hjson │ │ │ ├── quotes_strings_ml_result.json │ │ │ ├── quotes_strings_ml_test.json │ │ │ ├── quotes_strings_ml_testmeta.hjson │ │ │ ├── quotes_strings_result.hjson │ │ │ ├── quotes_strings_result.json │ │ │ ├── quotes_strings_test.hjson │ │ │ └── quotes_strings_testmeta.hjson │ │ ├── stringify1_result.hjson │ │ ├── stringify1_result.json │ │ ├── stringify1_test.hjson │ │ ├── strings2_result.hjson │ │ ├── strings2_result.json │ │ ├── strings2_test.hjson │ │ ├── strings_result.hjson │ │ ├── strings_result.json │ │ ├── strings_test.hjson │ │ ├── testlist.txt │ │ ├── trail_result.hjson │ │ ├── trail_result.json │ │ └── trail_test.hjson │ ├── test_bigint_as_string.py │ ├── test_bitsize_int_as_string.py │ ├── test_check_circular.py │ ├── test_decimal.py │ ├── test_decode.py │ ├── test_default.py │ ├── test_dump.py │ ├── test_encode_basestring_ascii.py │ ├── test_errors.py │ ├── test_fail.py │ ├── test_float.py │ ├── test_for_json.py │ ├── test_hjson.py │ ├── test_indent.py │ ├── test_item_sort_key.py │ ├── test_namedtuple.py │ ├── test_pass1.py │ ├── test_pass2.py │ ├── test_pass3.py │ ├── test_recursion.py │ ├── test_scanstring.py │ ├── test_separators.py │ ├── test_tool.py │ ├── test_tuple.py │ └── test_unicode.py └── tool.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | !__init__.py 2 | *.egg-info 3 | *.egg 4 | *.pyc 5 | *.so 6 | .DS_Store 7 | /MANIFEST 8 | /.coverage 9 | /coverage.xml 10 | /htmlcov 11 | /build 12 | /dist 13 | /docs 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7" 8 | - "pypy" 9 | script: 10 | - python -m compileall -f . 11 | - python setup.py test 12 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | hjson (based on simplejson) is dual-licensed software. It is available under the terms 2 | of the MIT license, or the Academic Free License version 2.1. The full 3 | text of each license agreement is included below. This code is also 4 | licensed to the Python Software Foundation (PSF) under a Contributor 5 | Agreement. 6 | 7 | MIT License 8 | =========== 9 | 10 | Copyright (c) 2006 Bob Ippolito 11 | Copyright (c) 2015 Christian Zangl 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy of 14 | this software and associated documentation files (the "Software"), to deal in 15 | the Software without restriction, including without limitation the rights to 16 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 17 | of the Software, and to permit persons to whom the Software is furnished to do 18 | so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | SOFTWARE. 30 | 31 | Academic Free License v. 2.1 32 | ============================ 33 | 34 | Copyright (c) 2006 Bob Ippolito. All rights reserved. 35 | Copyright (c) 2015 Christian Zangl 36 | 37 | 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: 38 | 39 | Licensed under the Academic Free License version 2.1 40 | 41 | 1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following: 42 | 43 | a) to reproduce the Original Work in copies; 44 | 45 | b) to prepare derivative works ("Derivative Works") based upon the Original Work; 46 | 47 | c) to distribute copies of the Original Work and Derivative Works to the public; 48 | 49 | d) to perform the Original Work publicly; and 50 | 51 | e) to display the Original Work publicly. 52 | 53 | 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. 54 | 55 | 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. 56 | 57 | 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. 58 | 59 | 5) This section intentionally omitted. 60 | 61 | 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. 62 | 63 | 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. 64 | 65 | 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. 66 | 67 | 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. 68 | 69 | 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. 70 | 71 | 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. 72 | 73 | 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. 74 | 75 | 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. 76 | 77 | 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. 78 | 79 | 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. 80 | 81 | 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. 82 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.py 2 | include *.txt 3 | include *.rst 4 | include MANIFEST.in 5 | prune \#* 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hjson-py 2 | 3 | [![Build Status](https://img.shields.io/travis/hjson/hjson-py.svg?style=flat-square)](http://travis-ci.org/hjson/hjson-py) 4 | [![PyPI version](https://img.shields.io/pypi/v/hjson.svg?style=flat-square)](https://pypi.python.org/pypi/hjson) 5 | 6 | [Hjson](https://hjson.github.io), a user interface for JSON 7 | 8 | ![Hjson Intro](https://hjson.github.io/hjson1.gif) 9 | 10 | Hjson works with Python 2.5+ and Python 3.3+ 11 | 12 | The Python implementation of Hjson is based on [simplejson](https://github.com/simplejson/simplejson). For other platforms see [hjson.github.io](https://hjson.github.io). 13 | 14 | # Installation 15 | 16 | - `pip install hjson` 17 | 18 | - or download from https://pypi.python.org/pypi/hjson 19 | 20 | pip will also add the `hjson` tool to your `PATH` (try `echo '{a:1}'|hjson`). 21 | 22 | ## Commandline 23 | 24 | ``` 25 | Usage: 26 | hjson [options] 27 | hjson [options] 28 | hjson (-h | --help) 29 | hjson (-V | --version) 30 | 31 | Options: 32 | -h --help Show this screen. 33 | -j Output as formatted JSON. 34 | -c Output as JSON. 35 | -V --version Show version. 36 | ``` 37 | 38 | E.g. `echo '{"json":"obj"}' | hjson` 39 | 40 | # Usage 41 | 42 | ```python 43 | import hjson 44 | ``` 45 | 46 | ## Decoding Hjson 47 | 48 | ```python 49 | text = """{ 50 | foo: a 51 | bar: 1 52 | }""" 53 | 54 | hjson.loads(text) 55 | ``` 56 | 57 | Result: 58 | ```python 59 | OrderedDict([('foo', 'a'), ('bar', 1)]) 60 | ``` 61 | 62 | ## Encoding Python object hierarchies 63 | 64 | ```python 65 | hjson.dumps({'foo': 'text', 'bar': (1, 2)}) 66 | ``` 67 | 68 | Result: 69 | ``` 70 | { 71 | foo: text 72 | bar: 73 | [ 74 | 1 75 | 2 76 | ] 77 | } 78 | ``` 79 | 80 | ## Encoding as JSON 81 | 82 | Note that this is probably not as performant as the simplejson version. 83 | 84 | ```python 85 | hjson.dumpsJSON(['foo', {'bar': ('baz', None, 1.0, 2)}]) 86 | ``` 87 | 88 | Result: 89 | `'["foo", {"bar": ["baz", null, 1.0, 2]}]'` 90 | 91 | 92 | 93 | # API 94 | 95 | [hjson-py documentation](http://hjson.github.io/hjson-py/) 96 | 97 | # History 98 | 99 | [see history.md](history.md) 100 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | hjson-py 2 | ======== 3 | 4 | `Hjson`_, a user interface for JSON 5 | 6 | Hjson works with Python 2.5+ and Python 3.3+ (based on `simplejson`_) 7 | 8 | Installation 9 | ============ 10 | 11 | - ``pip install hjson`` 12 | 13 | - or download from https://pypi.python.org/pypi/hjson 14 | 15 | Commandline 16 | ----------- 17 | 18 | :: 19 | 20 | Usage: 21 | hjson [options] 22 | hjson [options] 23 | hjson (-h | --help) 24 | hjson (-V | --version) 25 | 26 | Options: 27 | -h --help Show this screen. 28 | -j Output as formatted JSON. 29 | -c Output as JSON. 30 | -V --version Show version. 31 | 32 | E.g. ``echo '{"json":"obj"}' | hjson`` 33 | 34 | 35 | Usage 36 | ===== 37 | 38 | .. code-block:: python 39 | 40 | import hjson 41 | 42 | Decoding Hjson 43 | -------------- 44 | 45 | .. code-block:: python 46 | 47 | text = """{ 48 | foo: a 49 | bar: 1 50 | }""" 51 | 52 | hjson.loads(text) 53 | 54 | Result: 55 | 56 | .. code-block:: python 57 | 58 | OrderedDict([('foo', 'a'), ('bar', 1)]) 59 | 60 | Encoding Python object hierarchies 61 | ---------------------------------- 62 | 63 | .. code-block:: python 64 | 65 | hjson.dumps({'foo': 'text', 'bar': (1, 2)}) 66 | 67 | Result: 68 | 69 | :: 70 | 71 | { 72 | foo: text 73 | bar: 74 | [ 75 | 1 76 | 2 77 | ] 78 | } 79 | 80 | Encoding as JSON 81 | ---------------- 82 | 83 | Note that this is probably not as performant as the simplejson version. 84 | 85 | .. code-block:: python 86 | 87 | hjson.dumpsJSON(['foo', {'bar': ('baz', None, 1.0, 2)}]) 88 | 89 | Result: ``'["foo", {"bar": ["baz", null, 1.0, 2]}]'`` 90 | 91 | API 92 | === 93 | 94 | `hjson-py`_ 95 | 96 | .. _Hjson: https://hjson.github.io 97 | .. _simplejson: https://github.com/simplejson/simplejson 98 | .. _hjson-py: http://hjson.github.io/hjson-py/ 99 | -------------------------------------------------------------------------------- /history.md: -------------------------------------------------------------------------------- 1 | # History 2 | 3 | - v3.1.0 4 | - New maintainer @groodt 5 | - Use entrypoints instead of scripts 6 | - Remove usage of pkg_resources 7 | - v3.0.2 8 | - Use relative import 9 | - Fix empty multiline strings 10 | - v3.0.1 11 | - change hjson (cli tool) to use unicode 12 | - v3.0.0 13 | - add support for single quoted strings 14 | - v2.0.7 15 | - multiline strings allow tabs 16 | - v2.0.6 17 | - add support for blank and comment only files 18 | - v2.0.5 19 | - fix stringify for strings staring with a punctuator char 20 | - v2.0.2 21 | - fix err on bad ML string 22 | - v2.0.1 23 | - move to hjson org 24 | - v2.0.0 25 | - fix quoteless string starting with punctuator 26 | - v1.5.8 27 | - add CLI scripts for pip 28 | - v1.5.6 29 | - fix dump for comment tokens in keyname 30 | - v1.5.4 31 | - fix decode/encode single JSON value files 32 | - v1.5.3 33 | - fix trailing whitespace in keyname 34 | - v1.5.2 35 | - fix trailing space in quoteless strings 36 | - v1.5.1 37 | - better error messages & root check 38 | - v1.5.0 39 | - Added support for optional root braces 40 | - v1.4.1 41 | - Added documentation, links. 42 | - v1.4.0 43 | - First release. 44 | -------------------------------------------------------------------------------- /hjson/compat.py: -------------------------------------------------------------------------------- 1 | """Python 3 compatibility shims 2 | """ 3 | import sys 4 | if sys.version_info[0] < 3: 5 | PY3 = False 6 | def b(s): 7 | return s 8 | def u(s): 9 | return unicode(s, 'unicode_escape') 10 | import cStringIO as StringIO 11 | StringIO = BytesIO = StringIO.StringIO 12 | text_type = unicode 13 | binary_type = str 14 | string_types = (basestring,) 15 | integer_types = (int, long) 16 | unichr = unichr 17 | reload_module = reload 18 | def fromhex(s): 19 | return s.decode('hex') 20 | 21 | else: 22 | PY3 = True 23 | if sys.version_info[:2] >= (3, 4): 24 | from importlib import reload as reload_module 25 | else: 26 | from imp import reload as reload_module 27 | import codecs 28 | def b(s): 29 | return codecs.latin_1_encode(s)[0] 30 | def u(s): 31 | return s 32 | import io 33 | StringIO = io.StringIO 34 | BytesIO = io.BytesIO 35 | text_type = str 36 | binary_type = bytes 37 | string_types = (str,) 38 | integer_types = (int,) 39 | 40 | def unichr(s): 41 | return u(chr(s)) 42 | 43 | def fromhex(s): 44 | return bytes.fromhex(s) 45 | 46 | long_type = integer_types[-1] 47 | -------------------------------------------------------------------------------- /hjson/decoder.py: -------------------------------------------------------------------------------- 1 | """Implementation of HjsonDecoder 2 | """ 3 | from __future__ import absolute_import 4 | import re 5 | import sys 6 | import struct 7 | from .compat import fromhex, b, u, text_type, binary_type, PY3, unichr 8 | from .scanner import HjsonDecodeError 9 | 10 | # NOTE (3.1.0): HjsonDecodeError may still be imported from this module for 11 | # compatibility, but it was never in the __all__ 12 | __all__ = ['HjsonDecoder'] 13 | 14 | FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL 15 | 16 | def _floatconstants(): 17 | _BYTES = fromhex('7FF80000000000007FF0000000000000') 18 | # The struct module in Python 2.4 would get frexp() out of range here 19 | # when an endian is specified in the format string. Fixed in Python 2.5+ 20 | if sys.byteorder != 'big': 21 | _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1] 22 | nan, inf = struct.unpack('dd', _BYTES) 23 | return nan, inf, -inf 24 | 25 | NaN, PosInf, NegInf = _floatconstants() 26 | 27 | WHITESPACE = ' \t\n\r' 28 | PUNCTUATOR = '{}[],:' 29 | 30 | NUMBER_RE = re.compile(r'[\t ]*(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?[\t ]*') 31 | STRINGCHUNK = re.compile(r'(.*?)([\'"\\\x00-\x1f])', FLAGS) 32 | BACKSLASH = { 33 | '"': u('"'), '\'': u('\''), '\\': u('\u005c'), '/': u('/'), 34 | 'b': u('\b'), 'f': u('\f'), 'n': u('\n'), 'r': u('\r'), 't': u('\t'), 35 | } 36 | 37 | DEFAULT_ENCODING = "utf-8" 38 | 39 | def getNext(s, end): 40 | while 1: 41 | # Use a slice to prevent IndexError from being raised 42 | ch = s[end:end + 1] 43 | # Skip whitespace. 44 | while ch in WHITESPACE: 45 | if ch == '': return ch, end 46 | end += 1 47 | ch = s[end:end + 1] 48 | 49 | # Hjson allows comments 50 | ch2 = s[end + 1:end + 2] 51 | if ch == '#' or ch == '/' and ch2 == '/': 52 | end = getEol(s, end) 53 | elif ch == '/' and ch2 == '*': 54 | end += 2 55 | ch = s[end] 56 | while ch != '' and not (ch == '*' and s[end + 1] == '/'): 57 | end += 1 58 | ch = s[end] 59 | if ch != '': 60 | end += 2 61 | else: 62 | break 63 | 64 | return ch, end 65 | 66 | def getEol(s, end): 67 | # skip until eol 68 | 69 | while 1: 70 | ch = s[end:end + 1] 71 | if ch == '\r' or ch == '\n' or ch == '': 72 | return end 73 | end += 1 74 | 75 | def skipIndent(s, end, n): 76 | ch = s[end:end + 1] 77 | while ch != '' and ch in " \t\r" and (n > 0 or n < 0): 78 | end += 1 79 | n -= 1 80 | ch = s[end:end + 1] 81 | return end 82 | 83 | 84 | def scanstring(s, end, encoding=None, strict=True, 85 | _b=BACKSLASH, _m=STRINGCHUNK.match, _join=u('').join, 86 | _PY3=PY3, _maxunicode=sys.maxunicode): 87 | """Scan the string s for a JSON string. End is the index of the 88 | character in s after the quote that started the JSON string. 89 | Unescapes all valid JSON string escape sequences and raises ValueError 90 | on attempt to decode an invalid string. If strict is False then literal 91 | control characters are allowed in the string. 92 | 93 | Returns a tuple of the decoded string and the index of the character in s 94 | after the end quote.""" 95 | if encoding is None: 96 | encoding = DEFAULT_ENCODING 97 | chunks = [] 98 | _append = chunks.append 99 | begin = end - 1 100 | # callers make sure that string starts with " or ' 101 | exitCh = s[begin] 102 | while 1: 103 | chunk = _m(s, end) 104 | if chunk is None: 105 | raise HjsonDecodeError( 106 | "Unterminated string starting at", s, begin) 107 | end = chunk.end() 108 | content, terminator = chunk.groups() 109 | # Content is contains zero or more unescaped string characters 110 | if content: 111 | if not _PY3 and not isinstance(content, text_type): 112 | content = text_type(content, encoding) 113 | _append(content) 114 | # Terminator is the end of string, a literal control character, 115 | # or a backslash denoting that an escape sequence follows 116 | if terminator == exitCh: 117 | break 118 | elif terminator == '"' or terminator == '\'': 119 | _append(terminator) 120 | continue 121 | elif terminator != '\\': 122 | if strict: 123 | msg = "Invalid control character %r at" 124 | raise HjsonDecodeError(msg, s, end) 125 | else: 126 | _append(terminator) 127 | continue 128 | try: 129 | esc = s[end] 130 | except IndexError: 131 | raise HjsonDecodeError( 132 | "Unterminated string starting at", s, begin) 133 | # If not a unicode escape sequence, must be in the lookup table 134 | if esc != 'u': 135 | try: 136 | char = _b[esc] 137 | except KeyError: 138 | msg = "Invalid \\X escape sequence %r" 139 | raise HjsonDecodeError(msg, s, end) 140 | end += 1 141 | else: 142 | # Unicode escape sequence 143 | msg = "Invalid \\uXXXX escape sequence" 144 | esc = s[end + 1:end + 5] 145 | escX = esc[1:2] 146 | if len(esc) != 4 or escX == 'x' or escX == 'X': 147 | raise HjsonDecodeError(msg, s, end - 1) 148 | try: 149 | uni = int(esc, 16) 150 | except ValueError: 151 | raise HjsonDecodeError(msg, s, end - 1) 152 | end += 5 153 | # Check for surrogate pair on UCS-4 systems 154 | # Note that this will join high/low surrogate pairs 155 | # but will also pass unpaired surrogates through 156 | if (_maxunicode > 65535 and 157 | uni & 0xfc00 == 0xd800 and 158 | s[end:end + 2] == '\\u'): 159 | esc2 = s[end + 2:end + 6] 160 | escX = esc2[1:2] 161 | if len(esc2) == 4 and not (escX == 'x' or escX == 'X'): 162 | try: 163 | uni2 = int(esc2, 16) 164 | except ValueError: 165 | raise HjsonDecodeError(msg, s, end) 166 | if uni2 & 0xfc00 == 0xdc00: 167 | uni = 0x10000 + (((uni - 0xd800) << 10) | 168 | (uni2 - 0xdc00)) 169 | end += 6 170 | char = unichr(uni) 171 | # Append the unescaped character 172 | _append(char) 173 | return _join(chunks), end 174 | 175 | def mlscanstring(s, end): 176 | """Scan a multiline string""" 177 | 178 | string = "" 179 | triple = 0 180 | 181 | # we are at ''' - get indent 182 | indent = 0 183 | while 1: 184 | ch = s[end-indent-1] 185 | if ch == '\n': break 186 | indent += 1 187 | 188 | # skip white/to (newline) 189 | end = skipIndent(s, end + 3, -1) 190 | 191 | ch = s[end] 192 | if ch == '\n': end = skipIndent(s, end + 1, indent) 193 | 194 | # When parsing multiline string values, we must look for ' characters 195 | while 1: 196 | ch = s[end:end + 1] 197 | if ch == '': 198 | raise HjsonDecodeError("Bad multiline string", s, end); 199 | elif ch == '\'': 200 | triple += 1 201 | end += 1 202 | if triple == 3: 203 | if string and string[-1] == '\n': 204 | string = string[:-1] # remove last EOL 205 | return string, end 206 | else: 207 | continue 208 | else: 209 | while triple > 0: 210 | string += '\'' 211 | triple -= 1 212 | 213 | if ch == '\n': 214 | string += ch 215 | end = skipIndent(s, end + 1, indent) 216 | else: 217 | if ch != '\r': 218 | string += ch 219 | end += 1 220 | 221 | def scantfnns(context, s, end): 222 | """Scan s until eol. return string, True, False or None""" 223 | 224 | chf, begin = getNext(s, end) 225 | end = begin 226 | 227 | if chf in PUNCTUATOR: 228 | raise HjsonDecodeError("Found a punctuator character when expecting a quoteless string (check your syntax)", s, end); 229 | 230 | while 1: 231 | ch = s[end:end + 1] 232 | 233 | isEol = ch == '\r' or ch == '\n' or ch == '' 234 | if isEol or ch == ',' or \ 235 | ch == '}' or ch == ']' or \ 236 | ch == '#' or \ 237 | ch == '/' and (s[end + 1:end + 2] == '/' or s[end + 1:end + 2] == '*'): 238 | 239 | m = None 240 | mend = end 241 | if next: mend -= 1 242 | 243 | if chf == 'n' and s[begin:end].strip() == 'null': 244 | return None, end 245 | elif chf == 't' and s[begin:end].strip() == 'true': 246 | return True, end 247 | elif chf == 'f' and s[begin:end].strip() == 'false': 248 | return False, end 249 | elif chf == '-' or chf >= '0' and chf <= '9': 250 | m = NUMBER_RE.match(s, begin) 251 | 252 | if m is not None and m.end() == end: 253 | integer, frac, exp = m.groups() 254 | if frac or exp: 255 | res = context.parse_float(integer + (frac or '') + (exp or '')) 256 | if int(res) == res and abs(res)<1e10: res = int(res) 257 | else: 258 | res = context.parse_int(integer) 259 | return res, end 260 | 261 | if isEol: 262 | return s[begin:end].strip(), end 263 | 264 | end += 1 265 | 266 | def scanKeyName(s, end, encoding=None, strict=True): 267 | """Scan the string s for a JSON/Hjson key. see scanstring""" 268 | 269 | ch, end = getNext(s, end) 270 | 271 | if ch == '"' or ch == '\'': 272 | return scanstring(s, end + 1, encoding, strict) 273 | 274 | begin = end 275 | space = -1 276 | while 1: 277 | ch = s[end:end + 1] 278 | 279 | if ch == '': 280 | raise HjsonDecodeError("Bad key name (eof)", s, end); 281 | elif ch == ':': 282 | if begin == end: 283 | raise HjsonDecodeError("Found ':' but no key name (for an empty key name use quotes)", s, begin) 284 | elif space >= 0: 285 | if space != end - 1: raise HjsonDecodeError("Found whitespace in your key name (use quotes to include)", s, space) 286 | return s[begin:end].rstrip(), end 287 | else: 288 | return s[begin:end], end 289 | elif ch in WHITESPACE: 290 | if space < 0 or space == end - 1: space = end 291 | elif ch == '{' or ch == '}' or ch == '[' or ch == ']' or ch == ',': 292 | raise HjsonDecodeError("Found '" + ch + "' where a key name was expected (check your syntax or use quotes if the key name includes {}[],: or whitespace)", s, begin) 293 | end += 1 294 | 295 | def make_scanner(context): 296 | parse_object = context.parse_object 297 | parse_array = context.parse_array 298 | parse_string = context.parse_string 299 | parse_mlstring = context.parse_mlstring 300 | parse_tfnns = context.parse_tfnns 301 | encoding = context.encoding 302 | strict = context.strict 303 | object_hook = context.object_hook 304 | object_pairs_hook = context.object_pairs_hook 305 | memo = context.memo 306 | 307 | def _scan_once(string, idx): 308 | try: 309 | ch = string[idx] 310 | except IndexError: 311 | raise HjsonDecodeError('Expecting value', string, idx) 312 | 313 | if ch == '"' or ch == '\'': 314 | if string[idx:idx + 3] == '\'\'\'': 315 | return parse_mlstring(string, idx) 316 | else: 317 | return parse_string(string, idx + 1, encoding, strict) 318 | elif ch == '{': 319 | return parse_object((string, idx + 1), encoding, strict, 320 | _scan_once, object_hook, object_pairs_hook, memo) 321 | elif ch == '[': 322 | return parse_array((string, idx + 1), _scan_once) 323 | 324 | return parse_tfnns(context, string, idx) 325 | 326 | def scan_once(string, idx): 327 | if idx < 0: raise HjsonDecodeError('Expecting value', string, idx) 328 | try: 329 | return _scan_once(string, idx) 330 | finally: 331 | memo.clear() 332 | 333 | def scan_object_once(string, idx): 334 | if idx < 0: raise HjsonDecodeError('Expecting value', string, idx) 335 | try: 336 | return parse_object((string, idx), encoding, strict, 337 | _scan_once, object_hook, object_pairs_hook, memo, True) 338 | finally: 339 | memo.clear() 340 | 341 | return scan_once, scan_object_once 342 | 343 | 344 | def JSONObject(state, encoding, strict, scan_once, object_hook, 345 | object_pairs_hook, memo=None, objectWithoutBraces=False): 346 | (s, end) = state 347 | # Backwards compatibility 348 | if memo is None: 349 | memo = {} 350 | memo_get = memo.setdefault 351 | pairs = [] 352 | 353 | ch, end = getNext(s, end) 354 | 355 | # Trivial empty object 356 | if not objectWithoutBraces and ch == '}': 357 | if object_pairs_hook is not None: 358 | result = object_pairs_hook(pairs) 359 | return result, end + 1 360 | pairs = {} 361 | if object_hook is not None: 362 | pairs = object_hook(pairs) 363 | return pairs, end + 1 364 | 365 | while True: 366 | key, end = scanKeyName(s, end, encoding, strict) 367 | key = memo_get(key, key) 368 | 369 | ch, end = getNext(s, end) 370 | if ch != ':': 371 | raise HjsonDecodeError("Expecting ':' delimiter", s, end) 372 | 373 | ch, end = getNext(s, end + 1) 374 | 375 | value, end = scan_once(s, end) 376 | pairs.append((key, value)) 377 | 378 | ch, end = getNext(s, end) 379 | 380 | if ch == ',': 381 | ch, end = getNext(s, end + 1) 382 | 383 | if objectWithoutBraces: 384 | if ch == '': break; 385 | else: 386 | if ch == '}': 387 | end += 1 388 | break 389 | 390 | ch, end = getNext(s, end) 391 | 392 | if object_pairs_hook is not None: 393 | result = object_pairs_hook(pairs) 394 | return result, end 395 | pairs = dict(pairs) 396 | if object_hook is not None: 397 | pairs = object_hook(pairs) 398 | return pairs, end 399 | 400 | def JSONArray(state, scan_once): 401 | (s, end) = state 402 | values = [] 403 | 404 | ch, end = getNext(s, end) 405 | 406 | # Look-ahead for trivial empty array 407 | if ch == ']': 408 | return values, end + 1 409 | elif ch == '': 410 | raise HjsonDecodeError("End of input while parsing an array (did you forget a closing ']'?)", s, end) 411 | _append = values.append 412 | while True: 413 | value, end = scan_once(s, end) 414 | _append(value) 415 | 416 | ch, end = getNext(s, end) 417 | if ch == ',': 418 | ch, end = getNext(s, end + 1) 419 | 420 | if ch == ']': 421 | end += 1 422 | break 423 | 424 | ch, end = getNext(s, end) 425 | 426 | return values, end 427 | 428 | 429 | class HjsonDecoder(object): 430 | """Hjson decoder 431 | 432 | Performs the following translations in decoding by default: 433 | 434 | +---------------+-------------------+ 435 | | JSON | Python | 436 | +===============+===================+ 437 | | object | dict | 438 | +---------------+-------------------+ 439 | | array | list | 440 | +---------------+-------------------+ 441 | | string | str, unicode | 442 | +---------------+-------------------+ 443 | | number (int) | int, long | 444 | +---------------+-------------------+ 445 | | number (real) | float | 446 | +---------------+-------------------+ 447 | | true | True | 448 | +---------------+-------------------+ 449 | | false | False | 450 | +---------------+-------------------+ 451 | | null | None | 452 | +---------------+-------------------+ 453 | 454 | """ 455 | 456 | def __init__(self, encoding=None, object_hook=None, parse_float=None, 457 | parse_int=None, strict=True, 458 | object_pairs_hook=None): 459 | """ 460 | *encoding* determines the encoding used to interpret any 461 | :class:`str` objects decoded by this instance (``'utf-8'`` by 462 | default). It has no effect when decoding :class:`unicode` objects. 463 | 464 | Note that currently only encodings that are a superset of ASCII work, 465 | strings of other encodings should be passed in as :class:`unicode`. 466 | 467 | *object_hook*, if specified, will be called with the result of every 468 | JSON object decoded and its return value will be used in place of the 469 | given :class:`dict`. This can be used to provide custom 470 | deserializations (e.g. to support JSON-RPC class hinting). 471 | 472 | *object_pairs_hook* is an optional function that will be called with 473 | the result of any object literal decode with an ordered list of pairs. 474 | The return value of *object_pairs_hook* will be used instead of the 475 | :class:`dict`. This feature can be used to implement custom decoders 476 | that rely on the order that the key and value pairs are decoded (for 477 | example, :func:`collections.OrderedDict` will remember the order of 478 | insertion). If *object_hook* is also defined, the *object_pairs_hook* 479 | takes priority. 480 | 481 | *parse_float*, if specified, will be called with the string of every 482 | JSON float to be decoded. By default, this is equivalent to 483 | ``float(num_str)``. This can be used to use another datatype or parser 484 | for JSON floats (e.g. :class:`decimal.Decimal`). 485 | 486 | *parse_int*, if specified, will be called with the string of every 487 | JSON int to be decoded. By default, this is equivalent to 488 | ``int(num_str)``. This can be used to use another datatype or parser 489 | for JSON integers (e.g. :class:`float`). 490 | 491 | *strict* controls the parser's behavior when it encounters an 492 | invalid control character in a string. The default setting of 493 | ``True`` means that unescaped control characters are parse errors, if 494 | ``False`` then control characters will be allowed in strings. 495 | 496 | """ 497 | if encoding is None: 498 | encoding = DEFAULT_ENCODING 499 | self.encoding = encoding 500 | self.object_hook = object_hook 501 | self.object_pairs_hook = object_pairs_hook 502 | self.parse_float = parse_float or float 503 | self.parse_int = parse_int or int 504 | self.strict = strict 505 | self.parse_object = JSONObject 506 | self.parse_array = JSONArray 507 | self.parse_string = scanstring 508 | self.parse_mlstring = mlscanstring 509 | self.parse_tfnns = scantfnns 510 | self.memo = {} 511 | (self.scan_once, self.scan_object_once) = make_scanner(self) 512 | 513 | def decode(self, s, _PY3=PY3): 514 | """Return the Python representation of ``s`` (a ``str`` or ``unicode`` 515 | instance containing a JSON document) 516 | 517 | """ 518 | if _PY3 and isinstance(s, binary_type): 519 | s = s.decode(self.encoding) 520 | obj, end = self.raw_decode(s) 521 | ch, end = getNext(s, end) 522 | if end != len(s): 523 | raise HjsonDecodeError("Extra data", s, end, len(s)) 524 | return obj 525 | 526 | def raw_decode(self, s, idx=0, _PY3=PY3): 527 | """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` 528 | beginning with a JSON document) and return a 2-tuple of the Python 529 | representation and the index in ``s`` where the document ended. 530 | Optionally, ``idx`` can be used to specify an offset in ``s`` where 531 | the JSON document begins. 532 | 533 | This can be used to decode a JSON document from a string that may 534 | have extraneous data at the end. 535 | 536 | """ 537 | if idx < 0: 538 | # Ensure that raw_decode bails on negative indexes, the regex 539 | # would otherwise mask this behavior. #98 540 | raise HjsonDecodeError('Expecting value', s, idx) 541 | if _PY3 and not isinstance(s, text_type): 542 | raise TypeError("Input string must be text") 543 | # strip UTF-8 bom 544 | if len(s) > idx: 545 | ord0 = ord(s[idx]) 546 | if ord0 == 0xfeff: 547 | idx += 1 548 | elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf': 549 | idx += 3 550 | 551 | start_index = idx 552 | ch, idx = getNext(s, idx) 553 | 554 | # If blank or comment only file, return dict 555 | if start_index == 0 and ch == '': 556 | return {}, 0 557 | 558 | if ch == '{' or ch == '[': 559 | return self.scan_once(s, idx) 560 | else: 561 | # assume we have a root object without braces 562 | try: 563 | return self.scan_object_once(s, idx) 564 | except HjsonDecodeError as e: 565 | # test if we are dealing with a single JSON value instead (true/false/null/num/"") 566 | try: 567 | return self.scan_once(s, idx) 568 | except: 569 | raise e 570 | -------------------------------------------------------------------------------- /hjson/encoder.py: -------------------------------------------------------------------------------- 1 | """Implementation of JSONEncoder 2 | """ 3 | from __future__ import absolute_import 4 | import re 5 | from operator import itemgetter 6 | from decimal import Decimal 7 | from .compat import u, unichr, binary_type, string_types, integer_types, PY3 8 | from .decoder import PosInf 9 | 10 | #ESCAPE = re.compile(ur'[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029]') 11 | # This is required because u() will mangle the string and ur'' isn't valid 12 | # python3 syntax 13 | ESCAPE = re.compile(u'[\\x00-\\x1f\\\\"\\b\\f\\n\\r\\t\u2028\u2029]') 14 | ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') 15 | HAS_UTF8 = re.compile(r'[\x80-\xff]') 16 | ESCAPE_DCT = { 17 | '\\': '\\\\', 18 | '"': '\\"', 19 | '\b': '\\b', 20 | '\f': '\\f', 21 | '\n': '\\n', 22 | '\r': '\\r', 23 | '\t': '\\t', 24 | } 25 | for i in range(0x20): 26 | #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i)) 27 | ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) 28 | for i in [0x2028, 0x2029]: 29 | ESCAPE_DCT.setdefault(unichr(i), '\\u%04x' % (i,)) 30 | 31 | FLOAT_REPR = repr 32 | 33 | def encode_basestring(s, _PY3=PY3, _q=u('"')): 34 | """Return a JSON representation of a Python string 35 | 36 | """ 37 | if _PY3: 38 | if isinstance(s, binary_type): 39 | s = s.decode('utf-8') 40 | else: 41 | if isinstance(s, str) and HAS_UTF8.search(s) is not None: 42 | s = s.decode('utf-8') 43 | def replace(match): 44 | return ESCAPE_DCT[match.group(0)] 45 | return _q + ESCAPE.sub(replace, s) + _q 46 | 47 | 48 | def py_encode_basestring_ascii(s, _PY3=PY3): 49 | """Return an ASCII-only JSON representation of a Python string 50 | 51 | """ 52 | if _PY3: 53 | if isinstance(s, binary_type): 54 | s = s.decode('utf-8') 55 | else: 56 | if isinstance(s, str) and HAS_UTF8.search(s) is not None: 57 | s = s.decode('utf-8') 58 | def replace(match): 59 | s = match.group(0) 60 | try: 61 | return ESCAPE_DCT[s] 62 | except KeyError: 63 | n = ord(s) 64 | if n < 0x10000: 65 | #return '\\u{0:04x}'.format(n) 66 | return '\\u%04x' % (n,) 67 | else: 68 | # surrogate pair 69 | n -= 0x10000 70 | s1 = 0xd800 | ((n >> 10) & 0x3ff) 71 | s2 = 0xdc00 | (n & 0x3ff) 72 | #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2) 73 | return '\\u%04x\\u%04x' % (s1, s2) 74 | return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' 75 | 76 | 77 | encode_basestring_ascii = ( 78 | py_encode_basestring_ascii) 79 | 80 | class JSONEncoder(object): 81 | """Extensible JSON encoder for Python data structures. 82 | 83 | Supports the following objects and types by default: 84 | 85 | +-------------------+---------------+ 86 | | Python | JSON | 87 | +===================+===============+ 88 | | dict, namedtuple | object | 89 | +-------------------+---------------+ 90 | | list, tuple | array | 91 | +-------------------+---------------+ 92 | | str, unicode | string | 93 | +-------------------+---------------+ 94 | | int, long, float | number | 95 | +-------------------+---------------+ 96 | | True | true | 97 | +-------------------+---------------+ 98 | | False | false | 99 | +-------------------+---------------+ 100 | | None | null | 101 | +-------------------+---------------+ 102 | 103 | To extend this to recognize other objects, subclass and implement a 104 | ``.default()`` method with another method that returns a serializable 105 | object for ``o`` if possible, otherwise it should call the superclass 106 | implementation (to raise ``TypeError``). 107 | 108 | """ 109 | item_separator = ', ' 110 | key_separator = ': ' 111 | 112 | def __init__(self, skipkeys=False, ensure_ascii=True, 113 | check_circular=True, sort_keys=False, 114 | indent=None, separators=None, encoding='utf-8', default=None, 115 | use_decimal=True, namedtuple_as_object=True, 116 | tuple_as_array=True, bigint_as_string=False, 117 | item_sort_key=None, for_json=False, 118 | int_as_string_bitcount=None): 119 | """Constructor for JSONEncoder, with sensible defaults. 120 | 121 | If skipkeys is false, then it is a TypeError to attempt 122 | encoding of keys that are not str, int, long, float or None. If 123 | skipkeys is True, such items are simply skipped. 124 | 125 | If ensure_ascii is true, the output is guaranteed to be str 126 | objects with all incoming unicode characters escaped. If 127 | ensure_ascii is false, the output will be unicode object. 128 | 129 | If check_circular is true, then lists, dicts, and custom encoded 130 | objects will be checked for circular references during encoding to 131 | prevent an infinite recursion (which would cause an OverflowError). 132 | Otherwise, no such check takes place. 133 | 134 | If sort_keys is true, then the output of dictionaries will be 135 | sorted by key; this is useful for regression tests to ensure 136 | that JSON serializations can be compared on a day-to-day basis. 137 | 138 | If indent is a string, then JSON array elements and object members 139 | will be pretty-printed with a newline followed by that string repeated 140 | for each level of nesting. ``None`` (the default) selects the most compact 141 | representation without any newlines. For backwards compatibility with 142 | versions of hjson earlier than 2.1.0, an integer is also accepted 143 | and is converted to a string with that many spaces. 144 | 145 | If specified, separators should be an (item_separator, key_separator) 146 | tuple. The default is (', ', ': ') if *indent* is ``None`` and 147 | (',', ': ') otherwise. To get the most compact JSON representation, 148 | you should specify (',', ':') to eliminate whitespace. 149 | 150 | If specified, default is a function that gets called for objects 151 | that can't otherwise be serialized. It should return a JSON encodable 152 | version of the object or raise a ``TypeError``. 153 | 154 | If encoding is not None, then all input strings will be 155 | transformed into unicode using that encoding prior to JSON-encoding. 156 | The default is UTF-8. 157 | 158 | If use_decimal is true (not the default), ``decimal.Decimal`` will 159 | be supported directly by the encoder. For the inverse, decode JSON 160 | with ``parse_float=decimal.Decimal``. 161 | 162 | If namedtuple_as_object is true (the default), objects with 163 | ``_asdict()`` methods will be encoded as JSON objects. 164 | 165 | If tuple_as_array is true (the default), tuple (and subclasses) will 166 | be encoded as JSON arrays. 167 | 168 | If bigint_as_string is true (not the default), ints 2**53 and higher 169 | or lower than -2**53 will be encoded as strings. This is to avoid the 170 | rounding that happens in Javascript otherwise. 171 | 172 | If int_as_string_bitcount is a positive number (n), then int of size 173 | greater than or equal to 2**n or lower than or equal to -2**n will be 174 | encoded as strings. 175 | 176 | If specified, item_sort_key is a callable used to sort the items in 177 | each dictionary. This is useful if you want to sort items other than 178 | in alphabetical order by key. 179 | 180 | If for_json is true (not the default), objects with a ``for_json()`` 181 | method will use the return value of that method for encoding as JSON 182 | instead of the object. 183 | 184 | """ 185 | 186 | self.skipkeys = skipkeys 187 | self.ensure_ascii = ensure_ascii 188 | self.check_circular = check_circular 189 | self.sort_keys = sort_keys 190 | self.use_decimal = use_decimal 191 | self.namedtuple_as_object = namedtuple_as_object 192 | self.tuple_as_array = tuple_as_array 193 | self.bigint_as_string = bigint_as_string 194 | self.item_sort_key = item_sort_key 195 | self.for_json = for_json 196 | self.int_as_string_bitcount = int_as_string_bitcount 197 | if indent is not None and not isinstance(indent, string_types): 198 | indent = indent * ' ' 199 | self.indent = indent 200 | if separators is not None: 201 | self.item_separator, self.key_separator = separators 202 | elif indent is not None: 203 | self.item_separator = ',' 204 | if default is not None: 205 | self.default = default 206 | self.encoding = encoding 207 | 208 | def default(self, o): 209 | """Implement this method in a subclass such that it returns 210 | a serializable object for ``o``, or calls the base implementation 211 | (to raise a ``TypeError``). 212 | 213 | For example, to support arbitrary iterators, you could 214 | implement default like this:: 215 | 216 | def default(self, o): 217 | try: 218 | iterable = iter(o) 219 | except TypeError: 220 | pass 221 | else: 222 | return list(iterable) 223 | return JSONEncoder.default(self, o) 224 | 225 | """ 226 | raise TypeError(repr(o) + " is not JSON serializable") 227 | 228 | def encode(self, o): 229 | """Return a JSON string representation of a Python data structure. 230 | 231 | >>> from hjson import JSONEncoder 232 | >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) 233 | '{"foo": ["bar", "baz"]}' 234 | 235 | """ 236 | # This is for extremely simple cases and benchmarks. 237 | if isinstance(o, binary_type): 238 | _encoding = self.encoding 239 | if (_encoding is not None and not (_encoding == 'utf-8')): 240 | o = o.decode(_encoding) 241 | if isinstance(o, string_types): 242 | if self.ensure_ascii: 243 | return encode_basestring_ascii(o) 244 | else: 245 | return encode_basestring(o) 246 | # This doesn't pass the iterator directly to ''.join() because the 247 | # exceptions aren't as detailed. The list call should be roughly 248 | # equivalent to the PySequence_Fast that ''.join() would do. 249 | chunks = self.iterencode(o, _one_shot=True) 250 | if not isinstance(chunks, (list, tuple)): 251 | chunks = list(chunks) 252 | if self.ensure_ascii: 253 | return ''.join(chunks) 254 | else: 255 | return u''.join(chunks) 256 | 257 | def iterencode(self, o, _one_shot=False): 258 | """Encode the given object and yield each string 259 | representation as available. 260 | 261 | For example:: 262 | 263 | for chunk in JSONEncoder().iterencode(bigobject): 264 | mysocket.write(chunk) 265 | 266 | """ 267 | if self.check_circular: 268 | markers = {} 269 | else: 270 | markers = None 271 | if self.ensure_ascii: 272 | _encoder = encode_basestring_ascii 273 | else: 274 | _encoder = encode_basestring 275 | if self.encoding != 'utf-8': 276 | def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding): 277 | if isinstance(o, binary_type): 278 | o = o.decode(_encoding) 279 | return _orig_encoder(o) 280 | 281 | def floatstr(o, _repr=FLOAT_REPR, _inf=PosInf, _neginf=-PosInf): 282 | # Check for specials. Note that this type of test is processor 283 | # and/or platform-specific, so do tests which don't depend on 284 | # the internals. 285 | 286 | if o != o: 287 | text = 'null' 288 | elif o == _inf: 289 | text = 'null' 290 | elif o == _neginf: 291 | text = 'null' 292 | else: 293 | return _repr(o) 294 | 295 | return text 296 | 297 | key_memo = {} 298 | int_as_string_bitcount = ( 299 | 53 if self.bigint_as_string else self.int_as_string_bitcount) 300 | _iterencode = _make_iterencode( 301 | markers, self.default, _encoder, self.indent, floatstr, 302 | self.key_separator, self.item_separator, self.sort_keys, 303 | self.skipkeys, _one_shot, self.use_decimal, 304 | self.namedtuple_as_object, self.tuple_as_array, 305 | int_as_string_bitcount, 306 | self.item_sort_key, self.encoding, self.for_json, 307 | Decimal=Decimal) 308 | try: 309 | return _iterencode(o, 0) 310 | finally: 311 | key_memo.clear() 312 | 313 | 314 | def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, 315 | _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot, 316 | _use_decimal, _namedtuple_as_object, _tuple_as_array, 317 | _int_as_string_bitcount, _item_sort_key, 318 | _encoding,_for_json, 319 | ## HACK: hand-optimized bytecode; turn globals into locals 320 | _PY3=PY3, 321 | ValueError=ValueError, 322 | string_types=string_types, 323 | Decimal=Decimal, 324 | dict=dict, 325 | float=float, 326 | id=id, 327 | integer_types=integer_types, 328 | isinstance=isinstance, 329 | list=list, 330 | str=str, 331 | tuple=tuple, 332 | ): 333 | if _item_sort_key and not callable(_item_sort_key): 334 | raise TypeError("item_sort_key must be None or callable") 335 | elif _sort_keys and not _item_sort_key: 336 | _item_sort_key = itemgetter(0) 337 | 338 | if (_int_as_string_bitcount is not None and 339 | (_int_as_string_bitcount <= 0 or 340 | not isinstance(_int_as_string_bitcount, integer_types))): 341 | raise TypeError("int_as_string_bitcount must be a positive integer") 342 | 343 | def _encode_int(value): 344 | skip_quoting = ( 345 | _int_as_string_bitcount is None 346 | or 347 | _int_as_string_bitcount < 1 348 | ) 349 | if ( 350 | skip_quoting or 351 | (-1 << _int_as_string_bitcount) 352 | < value < 353 | (1 << _int_as_string_bitcount) 354 | ): 355 | return str(value) 356 | return '"' + str(value) + '"' 357 | 358 | def _iterencode_list(lst, _current_indent_level): 359 | if not lst: 360 | yield '[]' 361 | return 362 | if markers is not None: 363 | markerid = id(lst) 364 | if markerid in markers: 365 | raise ValueError("Circular reference detected") 366 | markers[markerid] = lst 367 | buf = '[' 368 | if _indent is not None: 369 | _current_indent_level += 1 370 | newline_indent = '\n' + (_indent * _current_indent_level) 371 | separator = _item_separator + newline_indent 372 | buf += newline_indent 373 | else: 374 | newline_indent = None 375 | separator = _item_separator 376 | first = True 377 | for value in lst: 378 | if first: 379 | first = False 380 | else: 381 | buf = separator 382 | yield buf 383 | 384 | for chunk in _iterencode(value, _current_indent_level): 385 | yield chunk 386 | 387 | if newline_indent is not None: 388 | _current_indent_level -= 1 389 | yield '\n' + (_indent * _current_indent_level) 390 | yield ']' 391 | if markers is not None: 392 | del markers[markerid] 393 | 394 | def _stringify_key(key): 395 | if isinstance(key, string_types): # pragma: no cover 396 | pass 397 | elif isinstance(key, binary_type): 398 | key = key.decode(_encoding) 399 | elif isinstance(key, float): 400 | key = _floatstr(key) 401 | elif key is True: 402 | key = 'true' 403 | elif key is False: 404 | key = 'false' 405 | elif key is None: 406 | key = 'null' 407 | elif isinstance(key, integer_types): 408 | key = str(key) 409 | elif _use_decimal and isinstance(key, Decimal): 410 | key = str(key) 411 | elif _skipkeys: 412 | key = None 413 | else: 414 | raise TypeError("key " + repr(key) + " is not a string") 415 | return key 416 | 417 | def _iterencode_dict(dct, _current_indent_level): 418 | if not dct: 419 | yield '{}' 420 | return 421 | if markers is not None: 422 | markerid = id(dct) 423 | if markerid in markers: 424 | raise ValueError("Circular reference detected") 425 | markers[markerid] = dct 426 | yield '{' 427 | if _indent is not None: 428 | _current_indent_level += 1 429 | newline_indent = '\n' + (_indent * _current_indent_level) 430 | item_separator = _item_separator + newline_indent 431 | yield newline_indent 432 | else: 433 | newline_indent = None 434 | item_separator = _item_separator 435 | first = True 436 | if _PY3: 437 | iteritems = dct.items() 438 | else: 439 | iteritems = dct.iteritems() 440 | if _item_sort_key: 441 | items = [] 442 | for k, v in dct.items(): 443 | if not isinstance(k, string_types): 444 | k = _stringify_key(k) 445 | if k is None: 446 | continue 447 | items.append((k, v)) 448 | items.sort(key=_item_sort_key) 449 | else: 450 | items = iteritems 451 | for key, value in items: 452 | if not (_item_sort_key or isinstance(key, string_types)): 453 | key = _stringify_key(key) 454 | if key is None: 455 | # _skipkeys must be True 456 | continue 457 | if first: 458 | first = False 459 | else: 460 | yield item_separator 461 | yield _encoder(key) 462 | yield _key_separator 463 | 464 | for chunk in _iterencode(value, _current_indent_level): 465 | yield chunk 466 | 467 | if newline_indent is not None: 468 | _current_indent_level -= 1 469 | yield '\n' + (_indent * _current_indent_level) 470 | yield '}' 471 | if markers is not None: 472 | del markers[markerid] 473 | 474 | def _iterencode(o, _current_indent_level): 475 | if (isinstance(o, string_types) or 476 | (_PY3 and isinstance(o, binary_type))): 477 | yield _encoder(o) 478 | elif o is None: 479 | yield 'null' 480 | elif o is True: 481 | yield 'true' 482 | elif o is False: 483 | yield 'false' 484 | elif isinstance(o, integer_types): 485 | yield _encode_int(o) 486 | elif isinstance(o, float): 487 | yield _floatstr(o) 488 | else: 489 | for_json = _for_json and getattr(o, 'for_json', None) 490 | if for_json and callable(for_json): 491 | for chunk in _iterencode(for_json(), _current_indent_level): 492 | yield chunk 493 | elif isinstance(o, list): 494 | for chunk in _iterencode_list(o, _current_indent_level): 495 | yield chunk 496 | else: 497 | _asdict = _namedtuple_as_object and getattr(o, '_asdict', None) 498 | if _asdict and callable(_asdict): 499 | for chunk in _iterencode_dict(_asdict(), _current_indent_level): 500 | yield chunk 501 | elif (_tuple_as_array and isinstance(o, tuple)): 502 | for chunk in _iterencode_list(o, _current_indent_level): 503 | yield chunk 504 | elif isinstance(o, dict): 505 | for chunk in _iterencode_dict(o, _current_indent_level): 506 | yield chunk 507 | elif _use_decimal and isinstance(o, Decimal): 508 | yield str(o) 509 | else: 510 | if markers is not None: 511 | markerid = id(o) 512 | if markerid in markers: 513 | raise ValueError("Circular reference detected") 514 | markers[markerid] = o 515 | o = _default(o) 516 | for chunk in _iterencode(o, _current_indent_level): 517 | yield chunk 518 | if markers is not None: 519 | del markers[markerid] 520 | 521 | return _iterencode 522 | -------------------------------------------------------------------------------- /hjson/ordered_dict.py: -------------------------------------------------------------------------------- 1 | """Drop-in replacement for collections.OrderedDict by Raymond Hettinger 2 | 3 | http://code.activestate.com/recipes/576693/ 4 | 5 | """ 6 | from UserDict import DictMixin 7 | 8 | # Modified from original to support Python 2.4, see 9 | # http://code.google.com/p/simplejson/issues/detail?id=53 10 | try: 11 | all 12 | except NameError: 13 | def all(seq): 14 | for elem in seq: 15 | if not elem: 16 | return False 17 | return True 18 | 19 | class OrderedDict(dict, DictMixin): 20 | 21 | def __init__(self, *args, **kwds): 22 | if len(args) > 1: 23 | raise TypeError('expected at most 1 arguments, got %d' % len(args)) 24 | try: 25 | self.__end 26 | except AttributeError: 27 | self.clear() 28 | self.update(*args, **kwds) 29 | 30 | def clear(self): 31 | self.__end = end = [] 32 | end += [None, end, end] # sentinel node for doubly linked list 33 | self.__map = {} # key --> [key, prev, next] 34 | dict.clear(self) 35 | 36 | def __setitem__(self, key, value): 37 | if key not in self: 38 | end = self.__end 39 | curr = end[1] 40 | curr[2] = end[1] = self.__map[key] = [key, curr, end] 41 | dict.__setitem__(self, key, value) 42 | 43 | def __delitem__(self, key): 44 | dict.__delitem__(self, key) 45 | key, prev, next = self.__map.pop(key) 46 | prev[2] = next 47 | next[1] = prev 48 | 49 | def __iter__(self): 50 | end = self.__end 51 | curr = end[2] 52 | while curr is not end: 53 | yield curr[0] 54 | curr = curr[2] 55 | 56 | def __reversed__(self): 57 | end = self.__end 58 | curr = end[1] 59 | while curr is not end: 60 | yield curr[0] 61 | curr = curr[1] 62 | 63 | def popitem(self, last=True): 64 | if not self: 65 | raise KeyError('dictionary is empty') 66 | # Modified from original to support Python 2.4, see 67 | # http://code.google.com/p/simplejson/issues/detail?id=53 68 | if last: 69 | key = reversed(self).next() 70 | else: 71 | key = iter(self).next() 72 | value = self.pop(key) 73 | return key, value 74 | 75 | def __reduce__(self): 76 | items = [[k, self[k]] for k in self] 77 | tmp = self.__map, self.__end 78 | del self.__map, self.__end 79 | inst_dict = vars(self).copy() 80 | self.__map, self.__end = tmp 81 | if inst_dict: 82 | return (self.__class__, (items,), inst_dict) 83 | return self.__class__, (items,) 84 | 85 | def keys(self): 86 | return list(self) 87 | 88 | setdefault = DictMixin.setdefault 89 | update = DictMixin.update 90 | pop = DictMixin.pop 91 | values = DictMixin.values 92 | items = DictMixin.items 93 | iterkeys = DictMixin.iterkeys 94 | itervalues = DictMixin.itervalues 95 | iteritems = DictMixin.iteritems 96 | 97 | def __repr__(self): 98 | if not self: 99 | return '%s()' % (self.__class__.__name__,) 100 | return '%s(%r)' % (self.__class__.__name__, self.items()) 101 | 102 | def copy(self): 103 | return self.__class__(self) 104 | 105 | @classmethod 106 | def fromkeys(cls, iterable, value=None): 107 | d = cls() 108 | for key in iterable: 109 | d[key] = value 110 | return d 111 | 112 | def __eq__(self, other): 113 | if isinstance(other, OrderedDict): 114 | return len(self)==len(other) and \ 115 | all(p==q for p, q in zip(self.items(), other.items())) 116 | return dict.__eq__(self, other) 117 | 118 | def __ne__(self, other): 119 | return not self == other 120 | -------------------------------------------------------------------------------- /hjson/scanner.py: -------------------------------------------------------------------------------- 1 | """JSON token scanner 2 | """ 3 | import re 4 | 5 | __all__ = ['HjsonDecodeError'] 6 | 7 | class HjsonDecodeError(ValueError): 8 | """Subclass of ValueError with the following additional properties: 9 | 10 | msg: The unformatted error message 11 | doc: The JSON document being parsed 12 | pos: The start index of doc where parsing failed 13 | end: The end index of doc where parsing failed (may be None) 14 | lineno: The line corresponding to pos 15 | colno: The column corresponding to pos 16 | endlineno: The line corresponding to end (may be None) 17 | endcolno: The column corresponding to end (may be None) 18 | 19 | """ 20 | # Note that this exception is used from _speedups 21 | def __init__(self, msg, doc, pos, end=None): 22 | ValueError.__init__(self, errmsg(msg, doc, pos, end=end)) 23 | self.msg = msg 24 | self.doc = doc 25 | self.pos = pos 26 | self.end = end 27 | self.lineno, self.colno = linecol(doc, pos) 28 | if end is not None: 29 | self.endlineno, self.endcolno = linecol(doc, end) 30 | else: 31 | self.endlineno, self.endcolno = None, None 32 | 33 | def __reduce__(self): 34 | return self.__class__, (self.msg, self.doc, self.pos, self.end) 35 | 36 | 37 | def linecol(doc, pos): 38 | lineno = doc.count('\n', 0, pos) + 1 39 | if lineno == 1: 40 | colno = pos + 1 41 | else: 42 | colno = pos - doc.rindex('\n', 0, pos) 43 | return lineno, colno 44 | 45 | 46 | def errmsg(msg, doc, pos, end=None): 47 | lineno, colno = linecol(doc, pos) 48 | msg = msg.replace('%r', repr(doc[pos:pos + 1])) 49 | if end is None: 50 | fmt = '%s: line %d column %d (char %d)' 51 | return fmt % (msg, lineno, colno, pos) 52 | endlineno, endcolno = linecol(doc, end) 53 | fmt = '%s: line %d column %d - line %d column %d (char %d - %d)' 54 | return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end) 55 | 56 | 57 | -------------------------------------------------------------------------------- /hjson/tests/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import unittest 3 | import doctest 4 | import sys 5 | 6 | 7 | def additional_tests(suite=None): 8 | import hjson 9 | import hjson.encoder 10 | import hjson.decoder 11 | if suite is None: 12 | suite = unittest.TestSuite() 13 | for mod in (hjson, hjson.encoder, hjson.decoder): 14 | suite.addTest(doctest.DocTestSuite(mod)) 15 | return suite 16 | 17 | 18 | def all_tests_suite(): 19 | def get_suite(): 20 | return additional_tests( 21 | unittest.TestLoader().loadTestsFromNames([ 22 | 'hjson.tests.test_hjson', 23 | 'hjson.tests.test_bitsize_int_as_string', 24 | 'hjson.tests.test_bigint_as_string', 25 | 'hjson.tests.test_check_circular', 26 | 'hjson.tests.test_decode', 27 | 'hjson.tests.test_default', 28 | 'hjson.tests.test_dump', 29 | 'hjson.tests.test_encode_basestring_ascii', 30 | 'hjson.tests.test_errors', 31 | 'hjson.tests.test_fail', 32 | 'hjson.tests.test_float', 33 | 'hjson.tests.test_indent', 34 | 'hjson.tests.test_pass1', 35 | 'hjson.tests.test_pass2', 36 | 'hjson.tests.test_pass3', 37 | 'hjson.tests.test_recursion', 38 | 'hjson.tests.test_scanstring', 39 | 'hjson.tests.test_separators', 40 | 'hjson.tests.test_unicode', 41 | 'hjson.tests.test_decimal', 42 | 'hjson.tests.test_tuple', 43 | 'hjson.tests.test_namedtuple', 44 | #'hjson.tests.test_tool', # fails on windows 45 | 'hjson.tests.test_for_json', 46 | ])) 47 | suite = get_suite() 48 | return suite 49 | 50 | 51 | def main(): 52 | runner = unittest.TextTestRunner(verbosity=1 + sys.argv.count('-v')) 53 | suite = all_tests_suite() 54 | raise SystemExit(not runner.run(suite).wasSuccessful()) 55 | 56 | 57 | if __name__ == '__main__': 58 | import os 59 | import sys 60 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) 61 | main() 62 | -------------------------------------------------------------------------------- /hjson/tests/assets/charset2_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | uescape: "\u0000,\u0001,\uffff" 3 | French: ° î â ê Î Â Ê é É è à ù È À Ù ë Ë ç Ç œ « » 4 | German: ä Ä ö Ö ü Ü ß 5 | Italian: ° é ç à è ì ò ù À È Ì Ò Ù 6 | Spanish: ñ Ñ ü Ü á é í ó ú Á É Í Ó Ú º ¿ ¡ 7 | hex: ģ䕧覫췯ꯍ 8 | } -------------------------------------------------------------------------------- /hjson/tests/assets/charset2_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "uescape": "\u0000,\u0001,￿", 3 | "French": "° î â ê Î Â Ê é É è à ù È À Ù ë Ë ç Ç œ « »", 4 | "German": "ä Ä ö Ö ü Ü ß", 5 | "Italian": "° é ç à è ì ò ù À È Ì Ò Ù", 6 | "Spanish": "ñ Ñ ü Ü á é í ó ú Á É Í Ó Ú º ¿ ¡", 7 | "hex": "ģ䕧覫췯ꯍ" 8 | } -------------------------------------------------------------------------------- /hjson/tests/assets/charset2_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | uescape: "\u0000,\u0001,\uffff" 3 | French: ° î â ê Î Â Ê é É è à ù È À Ù ë Ë ç Ç œ « » 4 | German: ä Ä ö Ö ü Ü ß 5 | Italian: ° é ç à è ì ò ù À È Ì Ò Ù 6 | Spanish: ñ Ñ ü Ü á é í ó ú Á É Í Ó Ú º ¿ ¡ 7 | hex: "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A" 8 | } 9 | -------------------------------------------------------------------------------- /hjson/tests/assets/charset_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | ql-ascii: ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 3 | js-ascii: ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 4 | ml-ascii: ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 5 | } -------------------------------------------------------------------------------- /hjson/tests/assets/charset_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "ql-ascii": "! \"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 3 | "js-ascii": "! \"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 4 | "ml-ascii": "! \"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" 5 | } -------------------------------------------------------------------------------- /hjson/tests/assets/charset_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | ql-ascii: ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 3 | js-ascii: "! \"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" 4 | ml-ascii: 5 | ''' 6 | ! "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 7 | ''' 8 | } 9 | -------------------------------------------------------------------------------- /hjson/tests/assets/comments_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo1: This is a string value. # part of the string 3 | foo2: This is a string value. 4 | bar1: This is a string value. // part of the string 5 | bar2: This is a string value. 6 | foobar1: This is a string value./* part of the string */ 7 | foobar2: This is a string value. 8 | rem1: "# test" 9 | rem2: "// test" 10 | rem3: "/* test */" 11 | num1: 0 12 | num2: 0 13 | num3: 2 14 | true1: true 15 | true2: true 16 | true3: true 17 | false1: false 18 | false2: false 19 | false3: false 20 | null1: null 21 | null2: null 22 | null3: null 23 | str1: 00 # part of the string 24 | str2: 00.0 // part of the string 25 | str3: 02 /* part of the string */ 26 | } -------------------------------------------------------------------------------- /hjson/tests/assets/comments_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo1": "This is a string value. # part of the string", 3 | "foo2": "This is a string value.", 4 | "bar1": "This is a string value. // part of the string", 5 | "bar2": "This is a string value.", 6 | "foobar1": "This is a string value./* part of the string */", 7 | "foobar2": "This is a string value.", 8 | "rem1": "# test", 9 | "rem2": "// test", 10 | "rem3": "/* test */", 11 | "num1": 0, 12 | "num2": 0, 13 | "num3": 2, 14 | "true1": true, 15 | "true2": true, 16 | "true3": true, 17 | "false1": false, 18 | "false2": false, 19 | "false3": false, 20 | "null1": null, 21 | "null2": null, 22 | "null3": null, 23 | "str1": "00 # part of the string", 24 | "str2": "00.0 // part of the string", 25 | "str3": "02 /* part of the string */" 26 | } -------------------------------------------------------------------------------- /hjson/tests/assets/comments_test.hjson: -------------------------------------------------------------------------------- 1 | // test 2 | # all 3 | // comment 4 | /* 5 | styles 6 | */ 7 | # with lf 8 | 9 | 10 | 11 | # ! 12 | 13 | { 14 | # hjson style comment 15 | foo1: This is a string value. # part of the string 16 | foo2: "This is a string value." # a comment 17 | 18 | // js style comment 19 | bar1: This is a string value. // part of the string 20 | bar2: "This is a string value." // a comment 21 | 22 | /* js block style comments */foobar1:/* more */This is a string value./* part of the string */ 23 | /* js block style comments */foobar2:/* more */"This is a string value."/* a comment */ 24 | 25 | rem1: "# test" 26 | rem2: "// test" 27 | rem3: "/* test */" 28 | 29 | num1: 0 # comment 30 | num2: 0.0 // comment 31 | num3: 2 /* comment */ 32 | 33 | true1: true # comment 34 | true2: true // comment 35 | true3: true /* comment */ 36 | 37 | false1: false # comment 38 | false2: false // comment 39 | false3: false /* comment */ 40 | 41 | null1: null # comment 42 | null2: null // comment 43 | null3: null /* comment */ 44 | 45 | str1: 00 # part of the string 46 | str2: 00.0 // part of the string 47 | str3: 02 /* part of the string */ 48 | } 49 | -------------------------------------------------------------------------------- /hjson/tests/assets/empty_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "": empty 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/empty_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "": "empty" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/empty_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "": empty 3 | } 4 | -------------------------------------------------------------------------------- /hjson/tests/assets/extra/notabs_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: "bar\tjoe\noki\tdoki\n\t\ttwo tabs" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/notabs_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar\tjoe\noki\tdoki\n\t\ttwo tabs" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/notabs_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar\tjoe\noki\tdoki\n\t\ttwo tabs" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/notabs_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | multiline: no-tabs 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/extra/root_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | database: 3 | { 4 | host: 127.0.0.1 5 | port: 555 6 | } 7 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/root_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "database": { 3 | "host": "127.0.0.1", 4 | "port": 555 5 | } 6 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/root_test.hjson: -------------------------------------------------------------------------------- 1 | // a object with the root braces omitted 2 | database: 3 | { 4 | host: 127.0.0.1 5 | port: 555 6 | } 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/extra/root_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | legacyRoot: true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/extra/separator_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: "bar", 3 | unicorn: "rainbow", 4 | cat: 1, 5 | hello: 6 | [ 7 | "world", 8 | "!" 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/separator_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/separator_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/extra/separator_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | separator: true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failCharset1_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid \u char 3 | char: "\uxxxx" 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON02_test.json: -------------------------------------------------------------------------------- 1 | ["Unclosed array" -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON05_test.json: -------------------------------------------------------------------------------- 1 | ["double extra comma",,] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON06_test.json: -------------------------------------------------------------------------------- 1 | [ , "<-- missing value"] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON07_test.json: -------------------------------------------------------------------------------- 1 | ["Comma after the close"], -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON08_test.json: -------------------------------------------------------------------------------- 1 | ["Extra close"]] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON10_test.json: -------------------------------------------------------------------------------- 1 | {"Extra value after close": true} "misplaced quoted value" -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON11_test.json: -------------------------------------------------------------------------------- 1 | {"Illegal expression": 1 + 2} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON12_test.json: -------------------------------------------------------------------------------- 1 | {"Illegal invocation": alert()} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON13_test.json: -------------------------------------------------------------------------------- 1 | {"Numbers cannot have leading zeroes": 013} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON14_test.json: -------------------------------------------------------------------------------- 1 | {"Numbers cannot be hex": 0x14} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON15_test.json: -------------------------------------------------------------------------------- 1 | ["Illegal backslash escape: \x15"] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON16_test.json: -------------------------------------------------------------------------------- 1 | [\naked] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON17_test.json: -------------------------------------------------------------------------------- 1 | ["Illegal backslash escape: \017"] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON19_test.json: -------------------------------------------------------------------------------- 1 | {"Missing colon" null} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON20_test.json: -------------------------------------------------------------------------------- 1 | {"Double colon":: null} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON21_test.json: -------------------------------------------------------------------------------- 1 | {"Comma instead of colon", null} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON22_test.json: -------------------------------------------------------------------------------- 1 | ["Colon instead of comma": false] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON23_test.json: -------------------------------------------------------------------------------- 1 | ["Bad value", truth] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON26_test.json: -------------------------------------------------------------------------------- 1 | ["tab\ character\ in\ string\ "] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON28_test.json: -------------------------------------------------------------------------------- 1 | ["line\ 2 | break"] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON29_test.json: -------------------------------------------------------------------------------- 1 | [0e] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON30_test.json: -------------------------------------------------------------------------------- 1 | [0e+] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON31_test.json: -------------------------------------------------------------------------------- 1 | [0e+-1] -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON32_test.json: -------------------------------------------------------------------------------- 1 | {"Comma instead if closing brace": true, -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON33_test.json: -------------------------------------------------------------------------------- 1 | ["mismatch"} -------------------------------------------------------------------------------- /hjson/tests/assets/failJSON34_test.json: -------------------------------------------------------------------------------- 1 | A quoteless string is OK, 2 | but two must be contained in an array. 3 | -------------------------------------------------------------------------------- /hjson/tests/assets/failKey1_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid name 3 | wrong name: 0 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failKey2_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid name 3 | {name: 0 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failKey3_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid name 3 | key,name: 0 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failKey4_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid name 3 | : 0 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failKey5_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid name 3 | '''foo''': 0 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failMLStr1_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid multiline string 3 | ml: ''' 4 | -------------------------------------------------------------------------------- /hjson/tests/assets/failObj1_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid obj 3 | noDelimiter 4 | { 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/failObj2_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid obj 3 | noEnd 4 | { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/failObj3_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # missing key 3 | 4 | [ 5 | test 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr1a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: ] 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr1b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: ]x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr1c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | ] 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr1d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | ]x 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr2a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: } 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr2b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: }x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr2c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | } 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr2d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | }x 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr3a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: { 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr3b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: {x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr3c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | { 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr3d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | {x 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr4a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: [ 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr4b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: [x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr4c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | [ 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr4d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | [x 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr5a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: : 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr5b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: :x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr5c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | : 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr5d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | foo 3 | # invalid quoteless string 4 | :x 5 | ] 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr6a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: , 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr6b_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid quoteless string 3 | ql: ,x 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr6c_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | # invalid quoteless string 3 | # note that if there were a preceding value the comma would 4 | # be allowed/ignored as a separator/trailing comma 5 | , 6 | ] 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr6d_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | # invalid quoteless string 3 | # note that if there were a preceding value the comma would 4 | # be allowed/ignored as a separator/trailing comma 5 | ,x 6 | ] 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr7a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid string containing a newline 3 | foo : " 4 | " 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/failStr8a_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # invalid ml-string 3 | foo : ""'text''' 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/assets/kan_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | numbers: 3 | [ 4 | 0 5 | 0 6 | 0 7 | 42 8 | 42.1 9 | -5 10 | -5.1 11 | 1701 12 | -1701 13 | 12.345 14 | -12.345 15 | ] 16 | native: 17 | [ 18 | true 19 | true 20 | false 21 | false 22 | null 23 | null 24 | ] 25 | strings: 26 | [ 27 | x 0 28 | .0 29 | 00 30 | 01 31 | 0 0 0 32 | 42 x 33 | 42.1 asdf 34 | 1.2.3 35 | -5 0 - 36 | -5.1 -- 37 | 17.01e2 + 38 | -17.01e2 : 39 | 12345e-3 @ 40 | -12345e-3 $ 41 | true true 42 | x true 43 | false false 44 | x false 45 | null null 46 | x null 47 | ] 48 | } -------------------------------------------------------------------------------- /hjson/tests/assets/kan_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "numbers": [ 3 | 0, 4 | 0, 5 | 0, 6 | 42, 7 | 42.1, 8 | -5, 9 | -5.1, 10 | 1701, 11 | -1701, 12 | 12.345, 13 | -12.345 14 | ], 15 | "native": [ 16 | true, 17 | true, 18 | false, 19 | false, 20 | null, 21 | null 22 | ], 23 | "strings": [ 24 | "x 0", 25 | ".0", 26 | "00", 27 | "01", 28 | "0 0 0", 29 | "42 x", 30 | "42.1 asdf", 31 | "1.2.3", 32 | "-5 0 -", 33 | "-5.1 --", 34 | "17.01e2 +", 35 | "-17.01e2 :", 36 | "12345e-3 @", 37 | "-12345e-3 $", 38 | "true true", 39 | "x true", 40 | "false false", 41 | "x false", 42 | "null null", 43 | "x null" 44 | ] 45 | } -------------------------------------------------------------------------------- /hjson/tests/assets/kan_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # the comma forces a whitespace check 3 | numbers: 4 | [ 5 | 0 6 | 0 , 7 | -0 8 | 42 , 9 | 42.1 , 10 | -5 11 | -5.1 12 | 17.01e2 13 | -17.01e2 14 | 12345e-3 , 15 | -12345e-3 , 16 | ] 17 | native: 18 | [ 19 | true , 20 | true 21 | false , 22 | false 23 | null , 24 | null 25 | ] 26 | strings: 27 | [ 28 | x 0 29 | .0 30 | 00 31 | 01 32 | 0 0 0 33 | 42 x 34 | 42.1 asdf 35 | 1.2.3 36 | -5 0 - 37 | -5.1 -- 38 | 17.01e2 + 39 | -17.01e2 : 40 | 12345e-3 @ 41 | -12345e-3 $ 42 | true true 43 | x true 44 | false false 45 | x false 46 | null null 47 | x null 48 | ] 49 | } 50 | -------------------------------------------------------------------------------- /hjson/tests/assets/keys_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | unquoted_key: test 3 | _unquoted: test 4 | test-key: test 5 | -test: test 6 | .key: test 7 | trailing: test 8 | trailing2: test 9 | "#c1": test 10 | "foo#bar": test 11 | "//bar": test 12 | "foo//bar": test 13 | "/*foo*/": test 14 | "foo/*foo*/bar": test 15 | "/*": test 16 | "foo/*bar": test 17 | "\"": test 18 | "foo\"bar": test 19 | "'''": test 20 | "foo'''bar": test 21 | "'": test 22 | "'foo": test 23 | "foo'bar": test 24 | ":": test 25 | "foo:bar": test 26 | "{": test 27 | "foo{bar": test 28 | "}": test 29 | "foo}bar": test 30 | "[": test 31 | "foo[bar": test 32 | "]": test 33 | "foo]bar": test 34 | nl1: test 35 | nl2: test 36 | nl3: test 37 | } -------------------------------------------------------------------------------- /hjson/tests/assets/keys_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "unquoted_key": "test", 3 | "_unquoted": "test", 4 | "test-key": "test", 5 | "-test": "test", 6 | ".key": "test", 7 | "trailing": "test", 8 | "trailing2": "test", 9 | "#c1": "test", 10 | "foo#bar": "test", 11 | "//bar": "test", 12 | "foo//bar": "test", 13 | "/*foo*/": "test", 14 | "foo/*foo*/bar": "test", 15 | "/*": "test", 16 | "foo/*bar": "test", 17 | "\"": "test", 18 | "foo\"bar": "test", 19 | "'''": "test", 20 | "foo'''bar": "test", 21 | "'": "test", 22 | "'foo": "test", 23 | "foo'bar": "test", 24 | ":": "test", 25 | "foo:bar": "test", 26 | "{": "test", 27 | "foo{bar": "test", 28 | "}": "test", 29 | "foo}bar": "test", 30 | "[": "test", 31 | "foo[bar": "test", 32 | "]": "test", 33 | "foo]bar": "test", 34 | "nl1": "test", 35 | "nl2": "test", 36 | "nl3": "test" 37 | } -------------------------------------------------------------------------------- /hjson/tests/assets/keys_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # unquoted keys 3 | unquoted_key: test 4 | _unquoted: test 5 | test-key: test 6 | -test: test 7 | .key: test 8 | # trailing spaces in key names are ignored 9 | trailing : test 10 | trailing2 : test 11 | # comment char in key name 12 | "#c1": test 13 | "foo#bar": test 14 | "//bar": test 15 | "foo//bar": test 16 | "/*foo*/": test 17 | "foo/*foo*/bar": test 18 | "/*": test 19 | "foo/*bar": test 20 | # quotes in key name 21 | "\"": test 22 | "foo\"bar": test 23 | "'''": test 24 | "foo'''bar": test 25 | "'": test 26 | "'foo": test 27 | "foo'bar": test 28 | # control char in key name 29 | ":": test 30 | "foo:bar": test 31 | "{": test 32 | "foo{bar": test 33 | "}": test 34 | "foo}bar": test 35 | "[": test 36 | "foo[bar": test 37 | "]": test 38 | "foo]bar": test 39 | # newline 40 | nl1: 41 | test 42 | nl2 43 | : 44 | test 45 | 46 | nl3 47 | 48 | : 49 | 50 | test 51 | } 52 | -------------------------------------------------------------------------------- /hjson/tests/assets/mltabs_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: 3 | ''' 4 | bar joe 5 | oki doki 6 | two tabs 7 | ''' 8 | } -------------------------------------------------------------------------------- /hjson/tests/assets/mltabs_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar\tjoe\noki\tdoki\n\t\ttwo tabs" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/mltabs_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar\tjoe\noki\tdoki\n\t\ttwo tabs" 3 | } 4 | -------------------------------------------------------------------------------- /hjson/tests/assets/oa_result.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | a 3 | {} 4 | {} 5 | [] 6 | [] 7 | { 8 | b: 1 9 | c: [] 10 | d: {} 11 | } 12 | [] 13 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/oa_result.json: -------------------------------------------------------------------------------- 1 | [ 2 | "a", 3 | {}, 4 | {}, 5 | [], 6 | [], 7 | { 8 | "b": 1, 9 | "c": [], 10 | "d": {} 11 | }, 12 | [] 13 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/oa_test.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | a 3 | {} 4 | {} 5 | [] 6 | [] 7 | { 8 | b: 1 9 | c: [] 10 | d: {} 11 | } 12 | [] 13 | ] 14 | -------------------------------------------------------------------------------- /hjson/tests/assets/pass1_result.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | JSON Test Pattern pass1 3 | { 4 | "object with 1 member": 5 | [ 6 | array with 1 element 7 | ] 8 | } 9 | {} 10 | [] 11 | -42 12 | true 13 | false 14 | null 15 | { 16 | integer: 1234567890 17 | real: -9876.54321 18 | e: 1.23456789e-13 19 | E: 1.23456789e+34 20 | -: 2.3456789012e+76 21 | zero: 0 22 | one: 1 23 | space: " " 24 | quote: '''"''' 25 | backslash: \ 26 | controls: "\b\f\n\r\t" 27 | slash: / & / 28 | alpha: abcdefghijklmnopqrstuvwyz 29 | ALPHA: ABCDEFGHIJKLMNOPQRSTUVWYZ 30 | digit: 0123456789 31 | 0123456789: digit 32 | special: `1~!@#$%^&*()_+-={':[,]}|;.? 33 | hex: ģ䕧覫췯ꯍ 34 | true: true 35 | false: false 36 | null: null 37 | array: [] 38 | object: {} 39 | address: 50 St. James Street 40 | url: http://www.JSON.org/ 41 | comment: "// /* */": " " 43 | " s p a c e d ": 44 | [ 45 | 1 46 | 2 47 | 3 48 | 4 49 | 5 50 | 6 51 | 7 52 | ] 53 | compact: 54 | [ 55 | 1 56 | 2 57 | 3 58 | 4 59 | 5 60 | 6 61 | 7 62 | ] 63 | jsontext: '''{"object with 1 member":["array with 1 element"]}''' 64 | quotes: " " %22 0x22 034 " 65 | "/\\\"쫾몾ꮘﳞ볚\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?": A key can be any string 66 | } 67 | 0.5 68 | 98.6 69 | 99.44 70 | 1066 71 | 10 72 | 1 73 | 0.1 74 | 1 75 | 2 76 | 2 77 | rosebud 78 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/pass1_result.json: -------------------------------------------------------------------------------- 1 | [ 2 | "JSON Test Pattern pass1", 3 | { 4 | "object with 1 member": [ 5 | "array with 1 element" 6 | ] 7 | }, 8 | {}, 9 | [], 10 | -42, 11 | true, 12 | false, 13 | null, 14 | { 15 | "integer": 1234567890, 16 | "real": -9876.54321, 17 | "e": 1.23456789e-13, 18 | "E": 1.23456789e+34, 19 | "-": 2.3456789012e+76, 20 | "zero": 0, 21 | "one": 1, 22 | "space": " ", 23 | "quote": "\"", 24 | "backslash": "\\", 25 | "controls": "\b\f\n\r\t", 26 | "slash": "/ & /", 27 | "alpha": "abcdefghijklmnopqrstuvwyz", 28 | "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", 29 | "digit": "0123456789", 30 | "0123456789": "digit", 31 | "special": "`1~!@#$%^&*()_+-={':[,]}|;.?", 32 | "hex": "ģ䕧覫췯ꯍ", 33 | "true": true, 34 | "false": false, 35 | "null": null, 36 | "array": [], 37 | "object": {}, 38 | "address": "50 St. James Street", 39 | "url": "http://www.JSON.org/", 40 | "comment": "// /* */": " ", 42 | " s p a c e d ": [ 43 | 1, 44 | 2, 45 | 3, 46 | 4, 47 | 5, 48 | 6, 49 | 7 50 | ], 51 | "compact": [ 52 | 1, 53 | 2, 54 | 3, 55 | 4, 56 | 5, 57 | 6, 58 | 7 59 | ], 60 | "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", 61 | "quotes": "" \" %22 0x22 034 "", 62 | "/\\\"쫾몾ꮘﳞ볚\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?": "A key can be any string" 63 | }, 64 | 0.5, 65 | 98.6, 66 | 99.44, 67 | 1066, 68 | 10, 69 | 1, 70 | 0.1, 71 | 1, 72 | 2, 73 | 2, 74 | "rosebud" 75 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/pass1_test.json: -------------------------------------------------------------------------------- 1 | [ 2 | "JSON Test Pattern pass1", 3 | {"object with 1 member":["array with 1 element"]}, 4 | {}, 5 | [], 6 | -42, 7 | true, 8 | false, 9 | null, 10 | { 11 | "integer": 1234567890, 12 | "real": -9876.543210, 13 | "e": 0.123456789e-12, 14 | "E": 1.234567890E+34, 15 | "-": 23456789012E66, 16 | "zero": 0, 17 | "one": 1, 18 | "space": " ", 19 | "quote": "\"", 20 | "backslash": "\\", 21 | "controls": "\b\f\n\r\t", 22 | "slash": "/ & \/", 23 | "alpha": "abcdefghijklmnopqrstuvwyz", 24 | "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", 25 | "digit": "0123456789", 26 | "0123456789": "digit", 27 | "special": "`1~!@#$%^&*()_+-={':[,]}|;.?", 28 | "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", 29 | "true": true, 30 | "false": false, 31 | "null": null, 32 | "array":[ ], 33 | "object":{ }, 34 | "address": "50 St. James Street", 35 | "url": "http://www.JSON.org/", 36 | "comment": "// /* */": " ", 38 | " s p a c e d " :[1,2 , 3 39 | 40 | , 41 | 42 | 4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7], 43 | "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", 44 | "quotes": "" \u0022 %22 0x22 034 "", 45 | "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?" 46 | : "A key can be any string" 47 | }, 48 | 0.5 ,98.6 49 | , 50 | 99.44 51 | , 52 | 53 | 1066, 54 | 1e1, 55 | 0.1e1, 56 | 1e-1, 57 | 1e00,2e+00,2e-00 58 | ,"rosebud"] -------------------------------------------------------------------------------- /hjson/tests/assets/pass2_result.hjson: -------------------------------------------------------------------------------- 1 | [ 2 | [ 3 | [ 4 | [ 5 | [ 6 | [ 7 | [ 8 | [ 9 | [ 10 | [ 11 | [ 12 | [ 13 | [ 14 | [ 15 | [ 16 | [ 17 | [ 18 | [ 19 | [ 20 | Not too deep 21 | ] 22 | ] 23 | ] 24 | ] 25 | ] 26 | ] 27 | ] 28 | ] 29 | ] 30 | ] 31 | ] 32 | ] 33 | ] 34 | ] 35 | ] 36 | ] 37 | ] 38 | ] 39 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/pass2_result.json: -------------------------------------------------------------------------------- 1 | [ 2 | [ 3 | [ 4 | [ 5 | [ 6 | [ 7 | [ 8 | [ 9 | [ 10 | [ 11 | [ 12 | [ 13 | [ 14 | [ 15 | [ 16 | [ 17 | [ 18 | [ 19 | [ 20 | "Not too deep" 21 | ] 22 | ] 23 | ] 24 | ] 25 | ] 26 | ] 27 | ] 28 | ] 29 | ] 30 | ] 31 | ] 32 | ] 33 | ] 34 | ] 35 | ] 36 | ] 37 | ] 38 | ] 39 | ] -------------------------------------------------------------------------------- /hjson/tests/assets/pass2_test.json: -------------------------------------------------------------------------------- 1 | [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]] -------------------------------------------------------------------------------- /hjson/tests/assets/pass3_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "JSON Test Pattern pass3": 3 | { 4 | "The outermost value": must be an object or array. 5 | "In this test": It is an object. 6 | } 7 | } -------------------------------------------------------------------------------- /hjson/tests/assets/pass3_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "JSON Test Pattern pass3": { 3 | "The outermost value": "must be an object or array.", 4 | "In this test": "It is an object." 5 | } 6 | } -------------------------------------------------------------------------------- /hjson/tests/assets/pass3_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "JSON Test Pattern pass3": { 3 | "The outermost value": "must be an object or array.", 4 | "In this test": "It is an object." 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /hjson/tests/assets/pass4_result.hjson: -------------------------------------------------------------------------------- 1 | 10 -------------------------------------------------------------------------------- /hjson/tests/assets/pass4_result.json: -------------------------------------------------------------------------------- 1 | 10 -------------------------------------------------------------------------------- /hjson/tests/assets/pass4_test.json: -------------------------------------------------------------------------------- 1 | 2 | 10 3 | -------------------------------------------------------------------------------- /hjson/tests/assets/passSingle_result.hjson: -------------------------------------------------------------------------------- 1 | allow quoteless strings -------------------------------------------------------------------------------- /hjson/tests/assets/passSingle_result.json: -------------------------------------------------------------------------------- 1 | "allow quoteless strings" -------------------------------------------------------------------------------- /hjson/tests/assets/passSingle_test.hjson: -------------------------------------------------------------------------------- 1 | allow quoteless strings -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_all_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar" 3 | "unicorn": "rainbow" 4 | "cat": 1 5 | "hello": 6 | [ 7 | "world" 8 | "!" 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_all_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_all_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_all_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | quotes: "all" 4 | } 5 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_always_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: "bar" 3 | unicorn: "rainbow" 4 | cat: 1 5 | hello: 6 | [ 7 | "world" 8 | "!" 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_always_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_always_test.hjson: -------------------------------------------------------------------------------- 1 | // Test if `always` keeps working as before 2 | { 3 | "foo": "bar", 4 | "unicorn": "rainbow", 5 | "cat": 1, 6 | "hello": [ 7 | "world", 8 | "!" 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_always_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | quotes: "always" 4 | } 5 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_keys_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "foo": bar 3 | "unicorn": rainbow 4 | "cat": 1 5 | "hello": 6 | [ 7 | world 8 | ! 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_keys_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_keys_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_keys_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | quotes: "keys" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_ml_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | unicorn: "foo\nbar\nrainbow" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_ml_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "unicorn": "foo\nbar\nrainbow" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_ml_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "unicorn": "foo\nbar\nrainbow" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_ml_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | quotes: strings 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: "bar" 3 | unicorn: "rainbow" 4 | cat: 1 5 | hello: 6 | [ 7 | "world" 8 | "!" 9 | ] 10 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "bar", 3 | "unicorn": "rainbow", 4 | "cat": 1, 5 | "hello": [ 6 | "world", 7 | "!" 8 | ] 9 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify/quotes_strings_testmeta.hjson: -------------------------------------------------------------------------------- 1 | { 2 | options: { 3 | quotes: "strings" 4 | } 5 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify1_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | quotes: 3 | { 4 | num1: "1,2" 5 | num2: "-1.1 ," 6 | num3: "1e10 ,2" 7 | num4: "-1e-10," 8 | kw1: "true," 9 | kw2: "false ," 10 | kw3: "null,123" 11 | close1: "1}" 12 | close1b: "1 }" 13 | close2: "1]" 14 | close2b: "1 ]" 15 | close3: "1," 16 | close3b: "1 ," 17 | comment1: "1#str" 18 | comment2: "1//str" 19 | comment3: "1/*str*/" 20 | punc1: "{" 21 | punc1b: "{foo" 22 | punc2: "}" 23 | punc2b: "}foo" 24 | punc3: "[" 25 | punc3b: "[foo" 26 | punc4: "]" 27 | punc4b: "]foo" 28 | punc5: "," 29 | punc5b: ",foo" 30 | punc6: ":" 31 | punc6b: ":foo" 32 | } 33 | noquotes: 34 | { 35 | num0: .1,2 36 | num1: 1.1.1,2 37 | num2: -.1, 38 | num3: 1e10e,2 39 | num4: -1e--10, 40 | kw1: true1, 41 | kw2: false0, 42 | kw3: null0, 43 | close1: a} 44 | close2: a] 45 | comment1: a#str 46 | comment2: a//str 47 | comment3: a/*str*/ 48 | } 49 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify1_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "quotes": { 3 | "num1": "1,2", 4 | "num2": "-1.1 ,", 5 | "num3": "1e10 ,2", 6 | "num4": "-1e-10,", 7 | "kw1": "true,", 8 | "kw2": "false ,", 9 | "kw3": "null,123", 10 | "close1": "1}", 11 | "close1b": "1 }", 12 | "close2": "1]", 13 | "close2b": "1 ]", 14 | "close3": "1,", 15 | "close3b": "1 ,", 16 | "comment1": "1#str", 17 | "comment2": "1//str", 18 | "comment3": "1/*str*/", 19 | "punc1": "{", 20 | "punc1b": "{foo", 21 | "punc2": "}", 22 | "punc2b": "}foo", 23 | "punc3": "[", 24 | "punc3b": "[foo", 25 | "punc4": "]", 26 | "punc4b": "]foo", 27 | "punc5": ",", 28 | "punc5b": ",foo", 29 | "punc6": ":", 30 | "punc6b": ":foo" 31 | }, 32 | "noquotes": { 33 | "num0": ".1,2", 34 | "num1": "1.1.1,2", 35 | "num2": "-.1,", 36 | "num3": "1e10e,2", 37 | "num4": "-1e--10,", 38 | "kw1": "true1,", 39 | "kw2": "false0,", 40 | "kw3": "null0,", 41 | "close1": "a}", 42 | "close2": "a]", 43 | "comment1": "a#str", 44 | "comment2": "a//str", 45 | "comment3": "a/*str*/" 46 | } 47 | } -------------------------------------------------------------------------------- /hjson/tests/assets/stringify1_test.hjson: -------------------------------------------------------------------------------- 1 | // test if stringify produces correct output 2 | { 3 | quotes: 4 | { 5 | num1: "1,2" 6 | num2: "-1.1 ," 7 | num3: "1e10 ,2" 8 | num4: "-1e-10," 9 | kw1: "true," 10 | kw2: "false ," 11 | kw3: "null,123" 12 | close1: "1}" 13 | close1b: "1 }" 14 | close2: "1]" 15 | close2b: "1 ]" 16 | close3: "1," 17 | close3b: "1 ," 18 | comment1: "1#str" 19 | comment2: "1//str" 20 | comment3: "1/*str*/" 21 | punc1: "{" 22 | punc1b: "{foo" 23 | punc2: "}" 24 | punc2b: "}foo" 25 | punc3: "[" 26 | punc3b: "[foo" 27 | punc4: "]" 28 | punc4b: "]foo" 29 | punc5: "," 30 | punc5b: ",foo" 31 | punc6: ":" 32 | punc6b: ":foo" 33 | } 34 | noquotes: 35 | { 36 | num0: ".1,2" 37 | num1: "1.1.1,2" 38 | num2: "-.1," 39 | num3: "1e10e,2" 40 | num4: "-1e--10," 41 | kw1: "true1," 42 | kw2: "false0," 43 | kw3: "null0," 44 | close1: "a}" 45 | close2: "a]" 46 | comment1: "a#str" 47 | comment2: "a//str" 48 | comment3: "a/*str*/" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /hjson/tests/assets/strings2_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | key1: a key in single quotes 3 | "key 2": a key in single quotes 4 | "key \"": a key in single quotes 5 | text: 6 | [ 7 | single quoted string 8 | '''You need quotes for escapes''' 9 | " untrimmed " 10 | "untrimmed " 11 | containing " double quotes 12 | containing " double quotes 13 | containing " double quotes 14 | '''"containing more " double quotes"''' 15 | containing ' single quotes 16 | containing ' single quotes 17 | containing ' single quotes 18 | "'containing more ' single quotes'" 19 | "'containing more ' single quotes'" 20 | "\n" 21 | " \n" 22 | "\n \n \n \n" 23 | "\t\n" 24 | ] 25 | foo3a: asdf''' 26 | foo3b: "'''asdf" 27 | foo4a: "asdf'''\nasdf" 28 | foo4b: "asdf\n'''asdf" 29 | } -------------------------------------------------------------------------------- /hjson/tests/assets/strings2_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "key1": "a key in single quotes", 3 | "key 2": "a key in single quotes", 4 | "key \"": "a key in single quotes", 5 | "text": [ 6 | "single quoted string", 7 | "You need quotes\tfor escapes", 8 | " untrimmed ", 9 | "untrimmed ", 10 | "containing \" double quotes", 11 | "containing \" double quotes", 12 | "containing \" double quotes", 13 | "\"containing more \" double quotes\"", 14 | "containing ' single quotes", 15 | "containing ' single quotes", 16 | "containing ' single quotes", 17 | "'containing more ' single quotes'", 18 | "'containing more ' single quotes'", 19 | "\n", 20 | " \n", 21 | "\n \n \n \n", 22 | "\t\n" 23 | ], 24 | "foo3a": "asdf'''", 25 | "foo3b": "'''asdf", 26 | "foo4a": "asdf'''\nasdf", 27 | "foo4b": "asdf\n'''asdf" 28 | } -------------------------------------------------------------------------------- /hjson/tests/assets/strings2_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # Hjson 3 allows the use of single quotes 3 | 4 | 'key1': a key in single quotes 5 | 'key 2': a key in single quotes 6 | 'key "': a key in single quotes 7 | 8 | text: [ 9 | 'single quoted string' 10 | 'You need quotes\tfor escapes' 11 | ' untrimmed ' 12 | 'untrimmed ' 13 | 'containing " double quotes' 14 | 'containing \" double quotes' 15 | "containing \" double quotes" 16 | '"containing more " double quotes"' 17 | 'containing \' single quotes' 18 | "containing ' single quotes" 19 | "containing \' single quotes" 20 | "'containing more ' single quotes'" 21 | "\'containing more \' single quotes\'" 22 | 23 | '\n' 24 | ' \n' 25 | '\n \n \n \n' 26 | '\t\n' 27 | ] 28 | 29 | # escapes/no escape 30 | 31 | foo3a: 'asdf\'\'\'' 32 | foo3b: '\'\'\'asdf' 33 | 34 | foo4a: 'asdf\'\'\'\nasdf' 35 | foo4b: 'asdf\n\'\'\'asdf' 36 | } 37 | -------------------------------------------------------------------------------- /hjson/tests/assets/strings_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | text1: This is a valid string value. 3 | text2: a \ is just a \ 4 | text3: '''You need quotes for escapes''' 5 | text4a: " untrimmed " 6 | text4b: " untrimmed" 7 | text4c: "untrimmed " 8 | notml1: "\n" 9 | notml2: " \n" 10 | notml3: "\n \n \n \n" 11 | notml4: "\t\n" 12 | multiline1: 13 | ''' 14 | first line 15 | indented line 16 | last line 17 | ''' 18 | multiline2: 19 | ''' 20 | first line 21 | indented line 22 | last line 23 | ''' 24 | multiline3: 25 | ''' 26 | first line 27 | indented line 28 | last line 29 | 30 | ''' 31 | foo1a: asdf\"'a\s\w 32 | foo1b: asdf\"'a\s\w 33 | foo1c: asdf\"'a\s\w 34 | foo2a: '''"asdf"''' 35 | foo2b: '''"asdf"''' 36 | foo3a: asdf''' 37 | foo3b: "'''asdf" 38 | foo4a: "asdf'''\nasdf" 39 | foo4b: "asdf\n'''asdf" 40 | arr: 41 | [ 42 | one 43 | two 44 | three 45 | four 46 | ] 47 | not: 48 | { 49 | number: 5 50 | negative: -4.2 51 | yes: true 52 | no: false 53 | null: null 54 | array: 55 | [ 56 | 1 57 | 2 58 | 3 59 | 4 60 | 5 61 | 6 62 | 7 63 | 8 64 | 9 65 | 0 66 | -1 67 | 0.5 68 | ] 69 | } 70 | special: 71 | { 72 | true: "true" 73 | false: "false" 74 | null: "null" 75 | one: "1" 76 | two: "2" 77 | minus: "-3" 78 | } 79 | } -------------------------------------------------------------------------------- /hjson/tests/assets/strings_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "text1": "This is a valid string value.", 3 | "text2": "a \\ is just a \\", 4 | "text3": "You need quotes\tfor escapes", 5 | "text4a": " untrimmed ", 6 | "text4b": " untrimmed", 7 | "text4c": "untrimmed ", 8 | "notml1": "\n", 9 | "notml2": " \n", 10 | "notml3": "\n \n \n \n", 11 | "notml4": "\t\n", 12 | "multiline1": "first line\n indented line\nlast line", 13 | "multiline2": "first line\n indented line\nlast line", 14 | "multiline3": "first line\n indented line\nlast line\n", 15 | "foo1a": "asdf\\\"'a\\s\\w", 16 | "foo1b": "asdf\\\"'a\\s\\w", 17 | "foo1c": "asdf\\\"'a\\s\\w", 18 | "foo2a": "\"asdf\"", 19 | "foo2b": "\"asdf\"", 20 | "foo3a": "asdf'''", 21 | "foo3b": "'''asdf", 22 | "foo4a": "asdf'''\nasdf", 23 | "foo4b": "asdf\n'''asdf", 24 | "arr": [ 25 | "one", 26 | "two", 27 | "three", 28 | "four" 29 | ], 30 | "not": { 31 | "number": 5, 32 | "negative": -4.2, 33 | "yes": true, 34 | "no": false, 35 | "null": null, 36 | "array": [ 37 | 1, 38 | 2, 39 | 3, 40 | 4, 41 | 5, 42 | 6, 43 | 7, 44 | 8, 45 | 9, 46 | 0, 47 | -1, 48 | 0.5 49 | ] 50 | }, 51 | "special": { 52 | "true": "true", 53 | "false": "false", 54 | "null": "null", 55 | "one": "1", 56 | "two": "2", 57 | "minus": "-3" 58 | } 59 | } -------------------------------------------------------------------------------- /hjson/tests/assets/strings_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | # simple 3 | 4 | text1: This is a valid string value. 5 | text2:a \ is just a \ 6 | 7 | text3: "You need quotes\tfor escapes" 8 | 9 | text4a: " untrimmed " 10 | text4b: " untrimmed" 11 | text4c: "untrimmed " 12 | 13 | notml1: "\n" 14 | notml2: " \n" 15 | notml3: "\n \n \n \n" 16 | notml4: "\t\n" 17 | 18 | # multiline string 19 | 20 | multiline1: 21 | ''' 22 | first line 23 | indented line 24 | last line 25 | ''' 26 | 27 | multiline2: 28 | '''first line 29 | indented line 30 | last line''' 31 | 32 | multiline3: 33 | ''' 34 | first line 35 | indented line 36 | last line 37 | 38 | ''' # trailing lf 39 | 40 | # escapes/no escape 41 | 42 | foo1a: asdf\"'a\s\w 43 | foo1b: '''asdf\"'a\s\w''' 44 | foo1c: "asdf\\\"'a\\s\\w" 45 | 46 | foo2a: "\"asdf\"" 47 | foo2b: '''"asdf"''' 48 | 49 | foo3a: "asdf'''" 50 | foo3b: "'''asdf" 51 | 52 | foo4a: "asdf'''\nasdf" 53 | foo4b: "asdf\n'''asdf" 54 | 55 | # in arrays 56 | arr: 57 | [ 58 | one 59 | two 60 | "three" 61 | '''four''' 62 | ] 63 | 64 | # not strings 65 | not: 66 | { 67 | number: 5 68 | negative: -4.2 69 | yes: true 70 | no: false 71 | null: null 72 | array: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, 0.5 ] 73 | } 74 | 75 | # special quoted 76 | special: 77 | { 78 | true: "true" 79 | false: "false" 80 | null: "null" 81 | one: "1" 82 | two: "2" 83 | minus: "-3" 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /hjson/tests/assets/testlist.txt: -------------------------------------------------------------------------------- 1 | charset2_test.hjson 2 | charset_test.hjson 3 | comments_test.hjson 4 | empty_test.hjson 5 | failCharset1_test.hjson 6 | failJSON02_test.json 7 | failJSON05_test.json 8 | failJSON06_test.json 9 | failJSON07_test.json 10 | failJSON08_test.json 11 | failJSON10_test.json 12 | failJSON11_test.json 13 | failJSON12_test.json 14 | failJSON13_test.json 15 | failJSON14_test.json 16 | failJSON15_test.json 17 | failJSON16_test.json 18 | failJSON17_test.json 19 | failJSON19_test.json 20 | failJSON20_test.json 21 | failJSON21_test.json 22 | failJSON22_test.json 23 | failJSON23_test.json 24 | failJSON26_test.json 25 | failJSON28_test.json 26 | failJSON29_test.json 27 | failJSON30_test.json 28 | failJSON31_test.json 29 | failJSON32_test.json 30 | failJSON33_test.json 31 | failJSON34_test.json 32 | failKey1_test.hjson 33 | failKey2_test.hjson 34 | failKey3_test.hjson 35 | failKey4_test.hjson 36 | failKey5_test.hjson 37 | failMLStr1_test.hjson 38 | failObj1_test.hjson 39 | failObj2_test.hjson 40 | failObj3_test.hjson 41 | failStr1a_test.hjson 42 | failStr1b_test.hjson 43 | failStr1c_test.hjson 44 | failStr1d_test.hjson 45 | failStr2a_test.hjson 46 | failStr2b_test.hjson 47 | failStr2c_test.hjson 48 | failStr2d_test.hjson 49 | failStr3a_test.hjson 50 | failStr3b_test.hjson 51 | failStr3c_test.hjson 52 | failStr3d_test.hjson 53 | failStr4a_test.hjson 54 | failStr4b_test.hjson 55 | failStr4c_test.hjson 56 | failStr4d_test.hjson 57 | failStr5a_test.hjson 58 | failStr5b_test.hjson 59 | failStr5c_test.hjson 60 | failStr5d_test.hjson 61 | failStr6a_test.hjson 62 | failStr6b_test.hjson 63 | failStr6c_test.hjson 64 | failStr6d_test.hjson 65 | failStr7a_test.hjson 66 | failStr8a_test.hjson 67 | kan_test.hjson 68 | keys_test.hjson 69 | mltabs_test.json 70 | oa_test.hjson 71 | pass1_test.json 72 | pass2_test.json 73 | pass3_test.json 74 | pass4_test.json 75 | passSingle_test.hjson 76 | stringify1_test.hjson 77 | strings2_test.hjson 78 | strings_test.hjson 79 | trail_test.hjson 80 | stringify/quotes_all_test.hjson 81 | stringify/quotes_always_test.hjson 82 | stringify/quotes_keys_test.hjson 83 | stringify/quotes_strings_ml_test.json 84 | stringify/quotes_strings_test.hjson 85 | extra/notabs_test.json 86 | extra/root_test.hjson 87 | extra/separator_test.json -------------------------------------------------------------------------------- /hjson/tests/assets/trail_result.hjson: -------------------------------------------------------------------------------- 1 | { 2 | foo: 0 -- this string starts at 0 and ends at 1, preceding and trailing whitespace is ignored -- 1 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/trail_result.json: -------------------------------------------------------------------------------- 1 | { 2 | "foo": "0 -- this string starts at 0 and ends at 1, preceding and trailing whitespace is ignored -- 1" 3 | } -------------------------------------------------------------------------------- /hjson/tests/assets/trail_test.hjson: -------------------------------------------------------------------------------- 1 | { 2 | // the following line contains trailing whitespace: 3 | foo: 0 -- this string starts at 0 and ends at 1, preceding and trailing whitespace is ignored -- 1 4 | } 5 | -------------------------------------------------------------------------------- /hjson/tests/test_bigint_as_string.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | 6 | class TestBigintAsString(TestCase): 7 | # Python 2.5, at least the one that ships on Mac OS X, calculates 8 | # 2 ** 53 as 0! It manages to calculate 1 << 53 correctly. 9 | values = [(200, 200), 10 | ((1 << 53) - 1, 9007199254740991), 11 | ((1 << 53), '9007199254740992'), 12 | ((1 << 53) + 1, '9007199254740993'), 13 | (-100, -100), 14 | ((-1 << 53), '-9007199254740992'), 15 | ((-1 << 53) - 1, '-9007199254740993'), 16 | ((-1 << 53) + 1, -9007199254740991)] 17 | 18 | options = ( 19 | {"bigint_as_string": True}, 20 | {"int_as_string_bitcount": 53} 21 | ) 22 | 23 | def test_ints(self): 24 | for opts in self.options: 25 | for val, expect in self.values: 26 | self.assertEqual( 27 | val, 28 | json.loads(json.dumpsJSON(val))) 29 | self.assertEqual( 30 | expect, 31 | json.loads(json.dumpsJSON(val, **opts))) 32 | 33 | def test_lists(self): 34 | for opts in self.options: 35 | for val, expect in self.values: 36 | val = [val, val] 37 | expect = [expect, expect] 38 | self.assertEqual( 39 | val, 40 | json.loads(json.dumpsJSON(val))) 41 | self.assertEqual( 42 | expect, 43 | json.loads(json.dumpsJSON(val, **opts))) 44 | 45 | def test_dicts(self): 46 | for opts in self.options: 47 | for val, expect in self.values: 48 | val = {'k': val} 49 | expect = {'k': expect} 50 | self.assertEqual( 51 | val, 52 | json.loads(json.dumpsJSON(val))) 53 | self.assertEqual( 54 | expect, 55 | json.loads(json.dumpsJSON(val, **opts))) 56 | 57 | def test_dict_keys(self): 58 | for opts in self.options: 59 | for val, _ in self.values: 60 | expect = {str(val): 'value'} 61 | val = {val: 'value'} 62 | self.assertEqual( 63 | expect, 64 | json.loads(json.dumpsJSON(val))) 65 | self.assertEqual( 66 | expect, 67 | json.loads(json.dumpsJSON(val, **opts))) 68 | -------------------------------------------------------------------------------- /hjson/tests/test_bitsize_int_as_string.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | 6 | class TestBitSizeIntAsString(TestCase): 7 | # Python 2.5, at least the one that ships on Mac OS X, calculates 8 | # 2 ** 31 as 0! It manages to calculate 1 << 31 correctly. 9 | values = [ 10 | (200, 200), 11 | ((1 << 31) - 1, (1 << 31) - 1), 12 | ((1 << 31), str(1 << 31)), 13 | ((1 << 31) + 1, str((1 << 31) + 1)), 14 | (-100, -100), 15 | ((-1 << 31), str(-1 << 31)), 16 | ((-1 << 31) - 1, str((-1 << 31) - 1)), 17 | ((-1 << 31) + 1, (-1 << 31) + 1), 18 | ] 19 | 20 | def test_invalid_counts(self): 21 | for n in ['foo', -1, 0, 1.0]: 22 | self.assertRaises( 23 | TypeError, 24 | json.dumpsJSON, 0, int_as_string_bitcount=n) 25 | 26 | def test_ints_outside_range_fails(self): 27 | self.assertNotEqual( 28 | str(1 << 15), 29 | json.loads(json.dumpsJSON(1 << 15, int_as_string_bitcount=16)), 30 | ) 31 | 32 | def test_ints(self): 33 | for val, expect in self.values: 34 | self.assertEqual( 35 | val, 36 | json.loads(json.dumpsJSON(val))) 37 | self.assertEqual( 38 | expect, 39 | json.loads(json.dumpsJSON(val, int_as_string_bitcount=31)), 40 | ) 41 | 42 | def test_lists(self): 43 | for val, expect in self.values: 44 | val = [val, val] 45 | expect = [expect, expect] 46 | self.assertEqual( 47 | val, 48 | json.loads(json.dumpsJSON(val))) 49 | self.assertEqual( 50 | expect, 51 | json.loads(json.dumpsJSON(val, int_as_string_bitcount=31))) 52 | 53 | def test_dicts(self): 54 | for val, expect in self.values: 55 | val = {'k': val} 56 | expect = {'k': expect} 57 | self.assertEqual( 58 | val, 59 | json.loads(json.dumpsJSON(val))) 60 | self.assertEqual( 61 | expect, 62 | json.loads(json.dumpsJSON(val, int_as_string_bitcount=31))) 63 | 64 | def test_dict_keys(self): 65 | for val, _ in self.values: 66 | expect = {str(val): 'value'} 67 | val = {val: 'value'} 68 | self.assertEqual( 69 | expect, 70 | json.loads(json.dumpsJSON(val))) 71 | self.assertEqual( 72 | expect, 73 | json.loads(json.dumpsJSON(val, int_as_string_bitcount=31))) 74 | -------------------------------------------------------------------------------- /hjson/tests/test_check_circular.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | import hjson as json 3 | 4 | def default_iterable(obj): 5 | return list(obj) 6 | 7 | class TestCheckCircular(TestCase): 8 | def test_circular_dict(self): 9 | dct = {} 10 | dct['a'] = dct 11 | self.assertRaises(ValueError, json.dumpsJSON, dct) 12 | 13 | def test_circular_list(self): 14 | lst = [] 15 | lst.append(lst) 16 | self.assertRaises(ValueError, json.dumpsJSON, lst) 17 | 18 | def test_circular_composite(self): 19 | dct2 = {} 20 | dct2['a'] = [] 21 | dct2['a'].append(dct2) 22 | self.assertRaises(ValueError, json.dumpsJSON, dct2) 23 | 24 | def test_circular_default(self): 25 | json.dumpsJSON([set()], default=default_iterable) 26 | self.assertRaises(TypeError, json.dumpsJSON, [set()]) 27 | 28 | def test_circular_off_default(self): 29 | json.dumpsJSON([set()], default=default_iterable, check_circular=False) 30 | self.assertRaises(TypeError, json.dumpsJSON, [set()], check_circular=False) 31 | -------------------------------------------------------------------------------- /hjson/tests/test_decimal.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | from decimal import Decimal 3 | from unittest import TestCase 4 | from hjson.compat import StringIO, reload_module 5 | 6 | import hjson as json 7 | 8 | class TestDecimal(TestCase): 9 | NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500" 10 | def dumps(self, obj, **kw): 11 | sio = StringIO() 12 | json.dumpJSON(obj, sio, **kw) 13 | res = json.dumpsJSON(obj, **kw) 14 | self.assertEqual(res, sio.getvalue()) 15 | return res 16 | 17 | def loads(self, s, **kw): 18 | sio = StringIO(s) 19 | res = json.loads(s, **kw) 20 | self.assertEqual(res, json.load(sio, **kw)) 21 | return res 22 | 23 | def test_decimal_encode(self): 24 | for d in map(Decimal, self.NUMS): 25 | self.assertEqual(self.dumps(d, use_decimal=True), str(d)) 26 | 27 | def test_decimal_decode(self): 28 | for s in self.NUMS: 29 | self.assertEqual(self.loads(s, parse_float=Decimal), Decimal(s)) 30 | 31 | def test_stringify_key(self): 32 | for d in map(Decimal, self.NUMS): 33 | v = {d: d} 34 | self.assertEqual( 35 | self.loads( 36 | self.dumps(v, use_decimal=True), parse_float=Decimal), 37 | {str(d): d}) 38 | 39 | def test_decimal_roundtrip(self): 40 | for d in map(Decimal, self.NUMS): 41 | # The type might not be the same (int and Decimal) but they 42 | # should still compare equal. 43 | for v in [d, [d], {'': d}]: 44 | self.assertEqual( 45 | self.loads( 46 | self.dumps(v, use_decimal=True), parse_float=Decimal), 47 | v) 48 | 49 | def test_decimal_defaults(self): 50 | d = Decimal('1.1') 51 | # use_decimal=True is the default 52 | self.assertRaises(TypeError, json.dumpsJSON, d, use_decimal=False) 53 | self.assertEqual('1.1', json.dumpsJSON(d)) 54 | self.assertEqual('1.1', json.dumpsJSON(d, use_decimal=True)) 55 | self.assertRaises(TypeError, json.dumpJSON, d, StringIO(), 56 | use_decimal=False) 57 | sio = StringIO() 58 | json.dumpJSON(d, sio) 59 | self.assertEqual('1.1', sio.getvalue()) 60 | sio = StringIO() 61 | json.dumpJSON(d, sio, use_decimal=True) 62 | self.assertEqual('1.1', sio.getvalue()) 63 | 64 | def test_decimal_reload(self): 65 | # Simulate a subinterpreter that reloads the Python modules but not 66 | # the C code https://github.com/simplejson/simplejson/issues/34 67 | global Decimal 68 | Decimal = reload_module(decimal).Decimal 69 | import hjson.encoder 70 | hjson.encoder.Decimal = Decimal 71 | self.test_decimal_roundtrip() 72 | -------------------------------------------------------------------------------- /hjson/tests/test_decode.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import decimal 4 | from unittest import TestCase 5 | 6 | import hjson as json 7 | from hjson import OrderedDict 8 | from hjson.compat import StringIO 9 | 10 | 11 | class TestDecode(TestCase): 12 | if not hasattr(TestCase, "assertIs"): 13 | 14 | def assertIs(self, a, b): 15 | self.assertTrue(a is b, "%r is %r" % (a, b)) 16 | 17 | def test_decimal(self): 18 | rval = json.loads("1.1", parse_float=decimal.Decimal) 19 | self.assertTrue(isinstance(rval, decimal.Decimal)) 20 | self.assertEqual(rval, decimal.Decimal("1.1")) 21 | 22 | def test_float(self): 23 | rval = json.loads("1", parse_int=float) 24 | self.assertTrue(isinstance(rval, float)) 25 | self.assertEqual(rval, 1.0) 26 | 27 | def test_decoder_optimizations(self): 28 | # Several optimizations were made that skip over calls to 29 | # the whitespace regex, so this test is designed to try and 30 | # exercise the uncommon cases. The array cases are already covered. 31 | rval = json.loads('{ "key" : "value" , "k":"v" }') 32 | self.assertEqual(rval, {"key": "value", "k": "v"}) 33 | 34 | def test_empty_objects(self): 35 | s = "{}" 36 | self.assertEqual(json.loads(s), eval(s)) 37 | s = "[]" 38 | self.assertEqual(json.loads(s), eval(s)) 39 | s = '""' 40 | self.assertEqual(json.loads(s), eval(s)) 41 | 42 | def test_object_pairs_hook(self): 43 | s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' 44 | p = [ 45 | ("xkd", 1), 46 | ("kcw", 2), 47 | ("art", 3), 48 | ("hxm", 4), 49 | ("qrt", 5), 50 | ("pad", 6), 51 | ("hoy", 7), 52 | ] 53 | self.assertEqual(json.loads(s), eval(s)) 54 | self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p) 55 | self.assertEqual(json.load(StringIO(s), object_pairs_hook=lambda x: x), p) 56 | od = json.loads(s, object_pairs_hook=OrderedDict) 57 | self.assertEqual(od, OrderedDict(p)) 58 | self.assertEqual(type(od), OrderedDict) 59 | # the object_pairs_hook takes priority over the object_hook 60 | self.assertEqual( 61 | json.loads(s, object_pairs_hook=OrderedDict, object_hook=lambda x: None), 62 | OrderedDict(p), 63 | ) 64 | 65 | def check_keys_reuse(self, source, loads): 66 | rval = loads(source) 67 | (a, b), (c, d) = sorted(rval[0]), sorted(rval[1]) 68 | self.assertIs(a, c) 69 | self.assertIs(b, d) 70 | 71 | def test_keys_reuse_str(self): 72 | s = u'[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]'.encode("utf8") 73 | self.check_keys_reuse(s, json.loads) 74 | 75 | def test_keys_reuse_unicode(self): 76 | s = u'[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]' 77 | self.check_keys_reuse(s, json.loads) 78 | 79 | def test_empty_strings(self): 80 | self.assertEqual(json.loads('""'), "") 81 | self.assertEqual(json.loads(u'""'), u"") 82 | self.assertEqual(json.loads('[""]'), [""]) 83 | self.assertEqual(json.loads(u'[""]'), [u""]) 84 | 85 | def test_multiline_string(self): 86 | s1 = """ 87 | 88 | hello: ''' 89 | 90 | ''' 91 | 92 | """ 93 | s2 = """ 94 | 95 | hello: ''' 96 | ''' 97 | 98 | """ 99 | s3 = """ 100 | 101 | hello: '''''' 102 | 103 | """ 104 | s4 = """ 105 | 106 | hello: '' 107 | 108 | """ 109 | s5 = """ 110 | 111 | hello: "" 112 | 113 | """ 114 | self.assertEqual(json.loads(s1), {"hello": ""}) 115 | self.assertEqual(json.loads(s2), {"hello": ""}) 116 | self.assertEqual(json.loads(s3), {"hello": ""}) 117 | self.assertEqual(json.loads(s4), {"hello": ""}) 118 | self.assertEqual(json.loads(s5), {"hello": ""}) 119 | 120 | def test_raw_decode(self): 121 | cls = json.decoder.HjsonDecoder 122 | self.assertEqual(({"a": {}}, 9), cls().raw_decode('{"a": {}}')) 123 | # http://code.google.com/p/simplejson/issues/detail?id=85 124 | self.assertEqual( 125 | ({"a": {}}, 9), cls(object_pairs_hook=dict).raw_decode('{"a": {}}') 126 | ) 127 | # https://github.com/simplejson/simplejson/pull/38 128 | self.assertEqual(({"a": {}}, 11), cls().raw_decode(' \n{"a": {}}')) 129 | 130 | def test_bounds_checking(self): 131 | # https://github.com/simplejson/simplejson/issues/98 132 | j = json.decoder.HjsonDecoder() 133 | for i in [4, 5, 6, -1, -2, -3, -4, -5, -6]: 134 | self.assertRaises(ValueError, j.scan_once, "1234", i) 135 | self.assertRaises(ValueError, j.raw_decode, "1234", i) 136 | x, y = sorted(["128931233", "472389423"], key=id) 137 | diff = id(x) - id(y) 138 | self.assertRaises(ValueError, j.scan_once, y, diff) 139 | self.assertRaises(ValueError, j.raw_decode, y, i) 140 | -------------------------------------------------------------------------------- /hjson/tests/test_default.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | class TestDefault(TestCase): 6 | def test_default(self): 7 | self.assertEqual( 8 | json.dumpsJSON(type, default=repr), 9 | json.dumpsJSON(repr(type))) 10 | -------------------------------------------------------------------------------- /hjson/tests/test_dump.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | from hjson.compat import StringIO, long_type, b, binary_type, PY3 3 | import hjson as json 4 | 5 | def as_text_type(s): 6 | if PY3 and isinstance(s, binary_type): 7 | return s.decode('ascii') 8 | return s 9 | 10 | class TestDump(TestCase): 11 | def test_dump(self): 12 | sio = StringIO() 13 | json.dumpJSON({}, sio) 14 | self.assertEqual(sio.getvalue(), '{}') 15 | 16 | def test_constants(self): 17 | for c in [None, True, False]: 18 | self.assertTrue(json.loads(json.dumpsJSON(c)) is c) 19 | self.assertTrue(json.loads(json.dumpsJSON([c]))[0] is c) 20 | self.assertTrue(json.loads(json.dumpsJSON({'a': c}))['a'] is c) 21 | 22 | def test_stringify_key(self): 23 | items = [(b('bytes'), 'bytes'), 24 | (1.0, '1.0'), 25 | (10, '10'), 26 | (True, 'true'), 27 | (False, 'false'), 28 | (None, 'null'), 29 | (long_type(100), '100')] 30 | for k, expect in items: 31 | self.assertEqual( 32 | json.loads(json.dumpsJSON({k: expect})), 33 | {expect: expect}) 34 | self.assertEqual( 35 | json.loads(json.dumpsJSON({k: expect}, sort_keys=True)), 36 | {expect: expect}) 37 | self.assertRaises(TypeError, json.dumpsJSON, {json: 1}) 38 | for v in [{}, {'other': 1}, {b('derp'): 1, 'herp': 2}]: 39 | for sort_keys in [False, True]: 40 | v0 = dict(v) 41 | v0[json] = 1 42 | v1 = dict((as_text_type(key), val) for (key, val) in v.items()) 43 | self.assertEqual( 44 | json.loads(json.dumpsJSON(v0, skipkeys=True, sort_keys=sort_keys)), 45 | v1) 46 | self.assertEqual( 47 | json.loads(json.dumpsJSON({'': v0}, skipkeys=True, sort_keys=sort_keys)), 48 | {'': v1}) 49 | self.assertEqual( 50 | json.loads(json.dumpsJSON([v0], skipkeys=True, sort_keys=sort_keys)), 51 | [v1]) 52 | 53 | def test_dumps(self): 54 | self.assertEqual(json.dumpsJSON({}), '{}') 55 | 56 | def test_encode_truefalse(self): 57 | self.assertEqual(json.dumpsJSON( 58 | {True: False, False: True}, sort_keys=True), 59 | '{"false": true, "true": false}') 60 | self.assertEqual( 61 | json.dumpsJSON( 62 | {2: 3.0, 63 | 4.0: long_type(5), 64 | False: 1, 65 | long_type(6): True, 66 | "7": 0}, 67 | sort_keys=True), 68 | '{"2": 3.0, "4.0": 5, "6": true, "7": 0, "false": 1}') 69 | 70 | def test_ordered_dict(self): 71 | # http://bugs.python.org/issue6105 72 | items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)] 73 | s = json.dumpsJSON(json.OrderedDict(items)) 74 | self.assertEqual( 75 | s, 76 | '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}') 77 | 78 | def test_indent_unknown_type_acceptance(self): 79 | """ 80 | A test against the regression mentioned at `github issue 29`_. 81 | 82 | The indent parameter should accept any type which pretends to be 83 | an instance of int or long when it comes to being multiplied by 84 | strings, even if it is not actually an int or long, for 85 | backwards compatibility. 86 | 87 | .. _github issue 29: 88 | http://github.com/simplejson/simplejson/issue/29 89 | """ 90 | 91 | class AwesomeInt(object): 92 | """An awesome reimplementation of integers""" 93 | 94 | def __init__(self, *args, **kwargs): 95 | if len(args) > 0: 96 | # [construct from literals, objects, etc.] 97 | # ... 98 | 99 | # Finally, if args[0] is an integer, store it 100 | if isinstance(args[0], int): 101 | self._int = args[0] 102 | 103 | # [various methods] 104 | 105 | def __mul__(self, other): 106 | # [various ways to multiply AwesomeInt objects] 107 | # ... finally, if the right-hand operand is not awesome enough, 108 | # try to do a normal integer multiplication 109 | if hasattr(self, '_int'): 110 | return self._int * other 111 | else: 112 | raise NotImplementedError("To do non-awesome things with" 113 | " this object, please construct it from an integer!") 114 | 115 | s = json.dumpsJSON([0, 1, 2], indent=AwesomeInt(3)) 116 | self.assertEqual(s, '[\n 0,\n 1,\n 2\n]') 117 | 118 | def test_accumulator(self): 119 | # the C API uses an accumulator that collects after 100,000 appends 120 | lst = [0] * 100000 121 | self.assertEqual(json.loads(json.dumpsJSON(lst)), lst) 122 | 123 | def test_sort_keys(self): 124 | # https://github.com/simplejson/simplejson/issues/106 125 | for num_keys in range(2, 32): 126 | p = dict((str(x), x) for x in range(num_keys)) 127 | sio = StringIO() 128 | json.dumpJSON(p, sio, sort_keys=True) 129 | self.assertEqual(sio.getvalue(), json.dumpsJSON(p, sort_keys=True)) 130 | self.assertEqual(json.loads(sio.getvalue()), p) 131 | -------------------------------------------------------------------------------- /hjson/tests/test_encode_basestring_ascii.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson.encoder 4 | from hjson.compat import b 5 | 6 | CASES = [ 7 | (u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'), 8 | (u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'), 9 | (u'controls', '"controls"'), 10 | (u'\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'), 11 | (u'{"object with 1 member":["array with 1 element"]}', '"{\\"object with 1 member\\":[\\"array with 1 element\\"]}"'), 12 | (u' s p a c e d ', '" s p a c e d "'), 13 | (u'\U0001d120', '"\\ud834\\udd20"'), 14 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'), 15 | (b('\xce\xb1\xce\xa9'), '"\\u03b1\\u03a9"'), 16 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'), 17 | (b('\xce\xb1\xce\xa9'), '"\\u03b1\\u03a9"'), 18 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'), 19 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'), 20 | (u"`1~!@#$%^&*()_+-={':[,]}|;.?", '"`1~!@#$%^&*()_+-={\':[,]}|;.?"'), 21 | (u'\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'), 22 | (u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'), 23 | ] 24 | 25 | class TestEncodeBaseStringAscii(TestCase): 26 | def test_py_encode_basestring_ascii(self): 27 | self._test_encode_basestring_ascii(hjson.encoder.encode_basestring_ascii) 28 | 29 | def _test_encode_basestring_ascii(self, encode_basestring_ascii): 30 | fname = encode_basestring_ascii.__name__ 31 | for input_string, expect in CASES: 32 | result = encode_basestring_ascii(input_string) 33 | #self.assertEqual(result, expect, 34 | # '{0!r} != {1!r} for {2}({3!r})'.format( 35 | # result, expect, fname, input_string)) 36 | self.assertEqual(result, expect, 37 | '%r != %r for %s(%r)' % (result, expect, fname, input_string)) 38 | 39 | def test_sorted_dict(self): 40 | items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)] 41 | s = hjson.dumpsJSON(dict(items), sort_keys=True) 42 | self.assertEqual(s, '{"five": 5, "four": 4, "one": 1, "three": 3, "two": 2}') 43 | -------------------------------------------------------------------------------- /hjson/tests/test_errors.py: -------------------------------------------------------------------------------- 1 | import sys, pickle 2 | from unittest import TestCase 3 | 4 | import hjson as json 5 | from hjson.compat import u, b 6 | 7 | class TestErrors(TestCase): 8 | def test_string_keys_error(self): 9 | data = [{'a': 'A', 'b': (2, 4), 'c': 3.0, ('d',): 'D tuple'}] 10 | self.assertRaises(TypeError, json.dumpsJSON, data) 11 | 12 | def test_decode_error(self): 13 | err = None 14 | try: 15 | json.loads('{}\na\nb') 16 | except json.HjsonDecodeError: 17 | err = sys.exc_info()[1] 18 | else: 19 | self.fail('Expected HjsonDecodeError') 20 | self.assertEqual(err.lineno, 2) 21 | self.assertEqual(err.colno, 1) 22 | self.assertEqual(err.endlineno, 3) 23 | self.assertEqual(err.endcolno, 2) 24 | 25 | def test_scan_error(self): 26 | err = None 27 | for t in (u, b): 28 | try: 29 | json.loads(t('{"asdf": "')) 30 | except json.HjsonDecodeError: 31 | err = sys.exc_info()[1] 32 | else: 33 | self.fail('Expected HjsonDecodeError') 34 | self.assertEqual(err.lineno, 1) 35 | self.assertEqual(err.colno, 10) 36 | 37 | def test_error_is_pickable(self): 38 | err = None 39 | try: 40 | json.loads('{}\na\nb') 41 | except json.HjsonDecodeError: 42 | err = sys.exc_info()[1] 43 | else: 44 | self.fail('Expected HjsonDecodeError') 45 | s = pickle.dumps(err) 46 | e = pickle.loads(s) 47 | 48 | self.assertEqual(err.msg, e.msg) 49 | self.assertEqual(err.doc, e.doc) 50 | self.assertEqual(err.pos, e.pos) 51 | self.assertEqual(err.end, e.end) 52 | -------------------------------------------------------------------------------- /hjson/tests/test_fail.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from unittest import TestCase 3 | 4 | import hjson as json 5 | 6 | # 2007-10-05 7 | JSONDOCS = [ 8 | # http://json.org/JSON_checker/test/fail1.json 9 | # '"A JSON payload should be an object or array, not a string."', 10 | # http://json.org/JSON_checker/test/fail2.json 11 | '["Unclosed array"', 12 | # http://json.org/JSON_checker/test/fail3.json 13 | #'{unquoted_key: "keys must be quoted"}', 14 | # http://json.org/JSON_checker/test/fail4.json 15 | # '["extra comma",]', 16 | # http://json.org/JSON_checker/test/fail5.json 17 | '["double extra comma",,]', 18 | # http://json.org/JSON_checker/test/fail6.json 19 | '[ , "<-- missing value"]', 20 | # http://json.org/JSON_checker/test/fail7.json 21 | '["Comma after the close"],', 22 | # http://json.org/JSON_checker/test/fail8.json 23 | '["Extra close"]]', 24 | # http://json.org/JSON_checker/test/fail9.json 25 | # '{"Extra comma": true,}', 26 | # http://json.org/JSON_checker/test/fail10.json 27 | '{"Extra value after close": true} "misplaced quoted value"', 28 | # http://json.org/JSON_checker/test/fail11.json 29 | '{"Illegal expression": 1 + 2}', 30 | # http://json.org/JSON_checker/test/fail12.json 31 | '{"Illegal invocation": alert()}', 32 | # http://json.org/JSON_checker/test/fail13.json 33 | '{"Numbers cannot have leading zeroes": 013}', 34 | # http://json.org/JSON_checker/test/fail14.json 35 | '{"Numbers cannot be hex": 0x14}', 36 | # http://json.org/JSON_checker/test/fail15.json 37 | '["Illegal backslash escape: \\x15"]', 38 | # http://json.org/JSON_checker/test/fail16.json 39 | '[\\naked]', 40 | # http://json.org/JSON_checker/test/fail17.json 41 | '["Illegal backslash escape: \\017"]', 42 | # http://json.org/JSON_checker/test/fail18.json 43 | # '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 44 | # http://json.org/JSON_checker/test/fail19.json 45 | '{"Missing colon" null}', 46 | # http://json.org/JSON_checker/test/fail20.json 47 | '{"Double colon":: null}', 48 | # http://json.org/JSON_checker/test/fail21.json 49 | '{"Comma instead of colon", null}', 50 | # http://json.org/JSON_checker/test/fail22.json 51 | '["Colon instead of comma": false]', 52 | # http://json.org/JSON_checker/test/fail23.json 53 | '["Bad value", truth]', 54 | # http://json.org/JSON_checker/test/fail24.json 55 | #"['single quote']", 56 | # http://json.org/JSON_checker/test/fail25.json 57 | '["\ttab\tcharacter\tin\tstring\t"]', 58 | # http://json.org/JSON_checker/test/fail26.json 59 | '["tab\\ character\\ in\\ string\\ "]', 60 | # http://json.org/JSON_checker/test/fail27.json 61 | '["line\nbreak"]', 62 | # http://json.org/JSON_checker/test/fail28.json 63 | '["line\\\nbreak"]', 64 | # http://json.org/JSON_checker/test/fail29.json 65 | '[0e]', 66 | # http://json.org/JSON_checker/test/fail30.json 67 | '[0e+]', 68 | # http://json.org/JSON_checker/test/fail31.json 69 | '[0e+-1]', 70 | # http://json.org/JSON_checker/test/fail32.json 71 | '{"Comma instead if closing brace": true,', 72 | # http://json.org/JSON_checker/test/fail33.json 73 | '["mismatch"}', 74 | # http://code.google.com/p/simplejson/issues/detail?id=3 75 | u'["A\u001FZ control characters in string"]', 76 | # misc based on coverage 77 | '{', 78 | '{]', 79 | '{"foo": "bar"]', 80 | '{"foo": "bar"', 81 | ] 82 | 83 | class TestFail(TestCase): 84 | def test_failures(self): 85 | for idx, doc in enumerate(JSONDOCS): 86 | idx = idx + 1 87 | try: 88 | json.loads(doc) 89 | except json.HjsonDecodeError: 90 | pass 91 | else: 92 | self.fail("Expected failure for fail%d.json: %r" % (idx, doc)) 93 | 94 | def test_array_decoder_issue46(self): 95 | # http://code.google.com/p/simplejson/issues/detail?id=46 96 | for doc in [u'[,]', '[,]']: 97 | try: 98 | json.loads(doc) 99 | except json.HjsonDecodeError: 100 | pass 101 | except Exception: 102 | e = sys.exc_info()[1] 103 | self.fail("Unexpected exception raised %r %s" % (e, e)) 104 | else: 105 | self.fail("Unexpected success parsing '[,]'") 106 | 107 | def test_truncated_input(self): 108 | test_cases = [ 109 | ('[', "End of input while parsing an array", 1), 110 | # ('[42', "Expecting ',' delimiter", 3), 111 | ('[42,', 'Expecting value', 4), 112 | ('["', 'Unterminated string starting at', 1), 113 | ('["spam', 'Unterminated string starting at', 1), 114 | # ('["spam"', "Expecting ',' delimiter", 7), 115 | ('["spam",', 'Expecting value', 8), 116 | ('{', 'Bad key name (eof)', 1), 117 | ('{"', 'Unterminated string starting at', 1), 118 | ('{"spam', 'Unterminated string starting at', 1), 119 | ('{"spam"', "Expecting ':' delimiter", 7), 120 | ('{"spam":', 'Expecting value', 8), 121 | # ('{"spam":42', "Expecting ',' delimiter", 10), 122 | ('{"spam":42,', 'Bad key name (eof)', 11), 123 | ('"', 'Unterminated string starting at', 0), 124 | ('"spam', 'Unterminated string starting at', 0), 125 | ('[,', "Found a punctuator character", 1), 126 | ] 127 | for data, msg, idx in test_cases: 128 | try: 129 | json.loads(data) 130 | except json.HjsonDecodeError: 131 | e = sys.exc_info()[1] 132 | self.assertEqual( 133 | e.msg[:len(msg)], 134 | msg, 135 | "%r doesn't start with %r for %r" % (e.msg, msg, data)) 136 | self.assertEqual( 137 | e.pos, idx, 138 | "pos %r != %r for %r" % (e.pos, idx, data)) 139 | except Exception: 140 | e = sys.exc_info()[1] 141 | self.fail("Unexpected exception raised %r %s" % (e, e)) 142 | else: 143 | self.fail("Unexpected success parsing '%r'" % (data,)) 144 | -------------------------------------------------------------------------------- /hjson/tests/test_float.py: -------------------------------------------------------------------------------- 1 | import math 2 | from unittest import TestCase 3 | from hjson.compat import long_type, text_type 4 | import hjson as json 5 | from hjson.decoder import NaN, PosInf, NegInf 6 | 7 | class TestFloat(TestCase): 8 | 9 | def test_degenerates_ignore(self): 10 | for f in (PosInf, NegInf, NaN): 11 | self.assertEqual(json.loads(json.dumpsJSON(f)), None) 12 | 13 | def test_floats(self): 14 | for num in [1617161771.7650001, math.pi, math.pi**100, 15 | math.pi**-100, 3.1]: 16 | self.assertEqual(float(json.dumpsJSON(num)), num) 17 | self.assertEqual(json.loads(json.dumpsJSON(num)), num) 18 | self.assertEqual(json.loads(text_type(json.dumpsJSON(num))), num) 19 | 20 | def test_ints(self): 21 | for num in [1, long_type(1), 1<<32, 1<<64]: 22 | self.assertEqual(json.dumpsJSON(num), str(num)) 23 | self.assertEqual(int(json.dumpsJSON(num)), num) 24 | self.assertEqual(json.loads(json.dumpsJSON(num)), num) 25 | self.assertEqual(json.loads(text_type(json.dumpsJSON(num))), num) 26 | -------------------------------------------------------------------------------- /hjson/tests/test_for_json.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import hjson as json 3 | 4 | 5 | class ForJson(object): 6 | def for_json(self): 7 | return {'for_json': 1} 8 | 9 | 10 | class NestedForJson(object): 11 | def for_json(self): 12 | return {'nested': ForJson()} 13 | 14 | 15 | class ForJsonList(object): 16 | def for_json(self): 17 | return ['list'] 18 | 19 | 20 | class DictForJson(dict): 21 | def for_json(self): 22 | return {'alpha': 1} 23 | 24 | 25 | class ListForJson(list): 26 | def for_json(self): 27 | return ['list'] 28 | 29 | 30 | class TestForJson(unittest.TestCase): 31 | def assertRoundTrip(self, obj, other, for_json=True): 32 | if for_json is None: 33 | # None will use the default 34 | s = json.dumpsJSON(obj) 35 | else: 36 | s = json.dumpsJSON(obj, for_json=for_json) 37 | self.assertEqual( 38 | json.loads(s), 39 | other) 40 | 41 | def test_for_json_encodes_stand_alone_object(self): 42 | self.assertRoundTrip( 43 | ForJson(), 44 | ForJson().for_json()) 45 | 46 | def test_for_json_encodes_object_nested_in_dict(self): 47 | self.assertRoundTrip( 48 | {'hooray': ForJson()}, 49 | {'hooray': ForJson().for_json()}) 50 | 51 | def test_for_json_encodes_object_nested_in_list_within_dict(self): 52 | self.assertRoundTrip( 53 | {'list': [0, ForJson(), 2, 3]}, 54 | {'list': [0, ForJson().for_json(), 2, 3]}) 55 | 56 | def test_for_json_encodes_object_nested_within_object(self): 57 | self.assertRoundTrip( 58 | NestedForJson(), 59 | {'nested': {'for_json': 1}}) 60 | 61 | def test_for_json_encodes_list(self): 62 | self.assertRoundTrip( 63 | ForJsonList(), 64 | ForJsonList().for_json()) 65 | 66 | def test_for_json_encodes_list_within_object(self): 67 | self.assertRoundTrip( 68 | {'nested': ForJsonList()}, 69 | {'nested': ForJsonList().for_json()}) 70 | 71 | def test_for_json_encodes_dict_subclass(self): 72 | self.assertRoundTrip( 73 | DictForJson(a=1), 74 | DictForJson(a=1).for_json()) 75 | 76 | def test_for_json_encodes_list_subclass(self): 77 | self.assertRoundTrip( 78 | ListForJson(['l']), 79 | ListForJson(['l']).for_json()) 80 | 81 | def test_for_json_ignored_if_not_true_with_dict_subclass(self): 82 | for for_json in (None, False): 83 | self.assertRoundTrip( 84 | DictForJson(a=1), 85 | {'a': 1}, 86 | for_json=for_json) 87 | 88 | def test_for_json_ignored_if_not_true_with_list_subclass(self): 89 | for for_json in (None, False): 90 | self.assertRoundTrip( 91 | ListForJson(['l']), 92 | ['l'], 93 | for_json=for_json) 94 | 95 | def test_raises_typeerror_if_for_json_not_true_with_object(self): 96 | self.assertRaises(TypeError, json.dumpsJSON, ForJson()) 97 | self.assertRaises(TypeError, json.dumpsJSON, ForJson(), for_json=False) 98 | -------------------------------------------------------------------------------- /hjson/tests/test_hjson.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | 3 | import os 4 | import sys 5 | import subprocess 6 | import tempfile 7 | import codecs # dump 8 | 9 | from unittest import TestCase 10 | 11 | import hjson 12 | 13 | class TestAssets(TestCase): 14 | 15 | def __init__(self, *args, **kwargs): 16 | super(TestAssets, self).__init__(*args, **kwargs) 17 | self.assetsDir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "assets") 18 | self.assets = self.load('testlist.txt', False).split('\n') 19 | self.maxDiff = None 20 | self.verma, self.vermi = sys.version_info[0:2] 21 | 22 | def load(self, name, cr): 23 | name = os.path.join(self.assetsDir, name) 24 | with open(name, 'rb') as f: 25 | text = f.read().decode('utf-8') 26 | text = text.replace('\r', '') 27 | if cr: text = text.replace('\n', '\r\n') 28 | return text 29 | 30 | def check(self, name, file, inputCr): 31 | text = self.load(file, inputCr) 32 | shouldFail = name[0:4] == "fail" 33 | 34 | try: 35 | data = hjson.loads(text) 36 | self.assertFalse(shouldFail, file) 37 | 38 | text1 = hjson.dumpsJSON(data) 39 | hjson1 = hjson.dumps(data, ensure_ascii=False); 40 | result = hjson.loads(self.load(name + "_result.json", inputCr)) 41 | text2 = hjson.dumpsJSON(result) 42 | hjson2 = self.load(name + "_result.hjson", False) 43 | 44 | # dbg 45 | # with open(name + "_dbg1.txt", "w") as tmp: tmp.write(hjson1.encode("utf-8")) 46 | # with open(name + "_dbg2.txt", "w") as tmp: tmp.write(hjson2.encode("utf-8")) 47 | # with codecs.open(name + "_dbg3.txt", 'w', 'utf-8') as tmp: hjson.dump(data, tmp) 48 | 49 | if self.verma>2 or self.vermi>6: 50 | # final check fails on py2.6 because of string formatting issues 51 | self.assertEqual(text2, text1, file) 52 | self.assertEqual(hjson2, hjson1, file) 53 | 54 | except hjson.HjsonDecodeError as e: 55 | if not shouldFail: 56 | self.fail("raised error on parsing %s: %r" % (file, e)) 57 | 58 | def test_files(self): 59 | for file in self.assets: 60 | name, sep, ext = file.partition("_test.") 61 | if name.startswith("stringify/quotes") or \ 62 | name.startswith("extra/"): continue # ignore/not supported 63 | 64 | self.check(name, file, True) 65 | self.check(name, file, False) 66 | -------------------------------------------------------------------------------- /hjson/tests/test_indent.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | import textwrap 3 | 4 | import hjson as json 5 | from hjson.compat import StringIO 6 | 7 | class TestIndent(TestCase): 8 | def test_indent(self): 9 | h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 10 | 'i-vhbjkhnth', 11 | {'nifty': 87}, {'field': 'yes', 'morefield': False} ] 12 | 13 | expect = textwrap.dedent("""\ 14 | [ 15 | \t[ 16 | \t\t"blorpie" 17 | \t], 18 | \t[ 19 | \t\t"whoops" 20 | \t], 21 | \t[], 22 | \t"d-shtaeou", 23 | \t"d-nthiouh", 24 | \t"i-vhbjkhnth", 25 | \t{ 26 | \t\t"nifty": 87 27 | \t}, 28 | \t{ 29 | \t\t"field": "yes", 30 | \t\t"morefield": false 31 | \t} 32 | ]""") 33 | 34 | 35 | d1 = json.dumpsJSON(h) 36 | d2 = json.dumpsJSON(h, indent='\t', sort_keys=True, separators=(',', ': ')) 37 | d3 = json.dumpsJSON(h, indent=' ', sort_keys=True, separators=(',', ': ')) 38 | d4 = json.dumpsJSON(h, indent=2, sort_keys=True, separators=(',', ': ')) 39 | 40 | h1 = json.loads(d1) 41 | h2 = json.loads(d2) 42 | h3 = json.loads(d3) 43 | h4 = json.loads(d4) 44 | 45 | self.assertEqual(h1, h) 46 | self.assertEqual(h2, h) 47 | self.assertEqual(h3, h) 48 | self.assertEqual(h4, h) 49 | self.assertEqual(d3, expect.replace('\t', ' ')) 50 | self.assertEqual(d4, expect.replace('\t', ' ')) 51 | # NOTE: Python 2.4 textwrap.dedent converts tabs to spaces, 52 | # so the following is expected to fail. Python 2.4 is not a 53 | # supported platform in hjson 2.1.0+. 54 | self.assertEqual(d2, expect) 55 | 56 | def test_indent0(self): 57 | h = {3: 1} 58 | def check(indent, expected): 59 | d1 = json.dumpsJSON(h, indent=indent) 60 | self.assertEqual(d1, expected) 61 | 62 | sio = StringIO() 63 | json.dumpJSON(h, sio, indent=indent) 64 | self.assertEqual(sio.getvalue(), expected) 65 | 66 | # indent=0 should emit newlines 67 | check(0, '{\n"3": 1\n}') 68 | # indent=None is more compact 69 | check(None, '{"3": 1}') 70 | 71 | def test_separators(self): 72 | lst = [1,2,3,4] 73 | expect = '[\n1,\n2,\n3,\n4\n]' 74 | expect_spaces = '[\n1, \n2, \n3, \n4\n]' 75 | # Ensure that separators still works 76 | self.assertEqual( 77 | expect_spaces, 78 | json.dumpsJSON(lst, indent=0, separators=(', ', ': '))) 79 | # Force the new defaults 80 | self.assertEqual( 81 | expect, 82 | json.dumpsJSON(lst, indent=0, separators=(',', ': '))) 83 | # Added in 2.1.4 84 | self.assertEqual( 85 | expect, 86 | json.dumpsJSON(lst, indent=0)) 87 | -------------------------------------------------------------------------------- /hjson/tests/test_item_sort_key.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | from operator import itemgetter 5 | 6 | class TestItemSortKey(TestCase): 7 | def test_simple_first(self): 8 | a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'} 9 | self.assertEqual( 10 | '{"a": 1, "c": 5, "crate": "dog", "jack": "jill", "pick": "axe", "zeak": "oh", "array": [1, 5, 6, 9], "tuple": [83, 12, 3]}', 11 | json.dumpsJSON(a, item_sort_key=json.simple_first)) 12 | 13 | def test_case(self): 14 | a = {'a': 1, 'c': 5, 'Jack': 'jill', 'pick': 'axe', 'Array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'} 15 | self.assertEqual( 16 | '{"Array": [1, 5, 6, 9], "Jack": "jill", "a": 1, "c": 5, "crate": "dog", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}', 17 | json.dumpsJSON(a, item_sort_key=itemgetter(0))) 18 | self.assertEqual( 19 | '{"a": 1, "Array": [1, 5, 6, 9], "c": 5, "crate": "dog", "Jack": "jill", "pick": "axe", "tuple": [83, 12, 3], "zeak": "oh"}', 20 | json.dumpsJSON(a, item_sort_key=lambda kv: kv[0].lower())) 21 | -------------------------------------------------------------------------------- /hjson/tests/test_namedtuple.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import unittest 3 | import hjson as json 4 | from hjson.compat import StringIO 5 | 6 | try: 7 | from collections import namedtuple 8 | except ImportError: 9 | class Value(tuple): 10 | def __new__(cls, *args): 11 | return tuple.__new__(cls, args) 12 | 13 | def _asdict(self): 14 | return {'value': self[0]} 15 | class Point(tuple): 16 | def __new__(cls, *args): 17 | return tuple.__new__(cls, args) 18 | 19 | def _asdict(self): 20 | return {'x': self[0], 'y': self[1]} 21 | else: 22 | Value = namedtuple('Value', ['value']) 23 | Point = namedtuple('Point', ['x', 'y']) 24 | 25 | class DuckValue(object): 26 | def __init__(self, *args): 27 | self.value = Value(*args) 28 | 29 | def _asdict(self): 30 | return self.value._asdict() 31 | 32 | class DuckPoint(object): 33 | def __init__(self, *args): 34 | self.point = Point(*args) 35 | 36 | def _asdict(self): 37 | return self.point._asdict() 38 | 39 | class DeadDuck(object): 40 | _asdict = None 41 | 42 | class DeadDict(dict): 43 | _asdict = None 44 | 45 | CONSTRUCTORS = [ 46 | lambda v: v, 47 | lambda v: [v], 48 | lambda v: [{'key': v}], 49 | ] 50 | 51 | class TestNamedTuple(unittest.TestCase): 52 | def test_namedtuple_dumps(self): 53 | for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]: 54 | d = v._asdict() 55 | self.assertEqual(d, json.loads(json.dumpsJSON(v))) 56 | self.assertEqual( 57 | d, 58 | json.loads(json.dumpsJSON(v, namedtuple_as_object=True))) 59 | self.assertEqual(d, json.loads(json.dumpsJSON(v, tuple_as_array=False))) 60 | self.assertEqual( 61 | d, 62 | json.loads(json.dumpsJSON(v, namedtuple_as_object=True, 63 | tuple_as_array=False))) 64 | 65 | def test_namedtuple_dumps_false(self): 66 | for v in [Value(1), Point(1, 2)]: 67 | l = list(v) 68 | self.assertEqual( 69 | l, 70 | json.loads(json.dumpsJSON(v, namedtuple_as_object=False))) 71 | self.assertRaises(TypeError, json.dumpsJSON, v, 72 | tuple_as_array=False, namedtuple_as_object=False) 73 | 74 | def test_namedtuple_dump(self): 75 | for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]: 76 | d = v._asdict() 77 | sio = StringIO() 78 | json.dumpJSON(v, sio) 79 | self.assertEqual(d, json.loads(sio.getvalue())) 80 | sio = StringIO() 81 | json.dumpJSON(v, sio, namedtuple_as_object=True) 82 | self.assertEqual( 83 | d, 84 | json.loads(sio.getvalue())) 85 | sio = StringIO() 86 | json.dumpJSON(v, sio, tuple_as_array=False) 87 | self.assertEqual(d, json.loads(sio.getvalue())) 88 | sio = StringIO() 89 | json.dumpJSON(v, sio, namedtuple_as_object=True, 90 | tuple_as_array=False) 91 | self.assertEqual( 92 | d, 93 | json.loads(sio.getvalue())) 94 | 95 | def test_namedtuple_dump_false(self): 96 | for v in [Value(1), Point(1, 2)]: 97 | l = list(v) 98 | sio = StringIO() 99 | json.dumpJSON(v, sio, namedtuple_as_object=False) 100 | self.assertEqual( 101 | l, 102 | json.loads(sio.getvalue())) 103 | self.assertRaises(TypeError, json.dumpJSON, v, StringIO(), 104 | tuple_as_array=False, namedtuple_as_object=False) 105 | 106 | def test_asdict_not_callable_dump(self): 107 | for f in CONSTRUCTORS: 108 | self.assertRaises(TypeError, 109 | json.dumpJSON, f(DeadDuck()), StringIO(), namedtuple_as_object=True) 110 | sio = StringIO() 111 | json.dumpJSON(f(DeadDict()), sio, namedtuple_as_object=True) 112 | self.assertEqual( 113 | json.dumpsJSON(f({})), 114 | sio.getvalue()) 115 | 116 | def test_asdict_not_callable_dumps(self): 117 | for f in CONSTRUCTORS: 118 | self.assertRaises(TypeError, 119 | json.dumpsJSON, f(DeadDuck()), namedtuple_as_object=True) 120 | self.assertEqual( 121 | json.dumpsJSON(f({})), 122 | json.dumpsJSON(f(DeadDict()), namedtuple_as_object=True)) 123 | -------------------------------------------------------------------------------- /hjson/tests/test_pass1.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | # from http://json.org/JSON_checker/test/pass1.json 6 | JSON = r''' 7 | [ 8 | "JSON Test Pattern pass1", 9 | {"object with 1 member":["array with 1 element"]}, 10 | {}, 11 | [], 12 | -42, 13 | true, 14 | false, 15 | null, 16 | { 17 | "integer": 1234567890, 18 | "real": -9876.543210, 19 | "e": 0.123456789e-12, 20 | "E": 1.234567890E+34, 21 | "": 23456789012E66, 22 | "zero": 0, 23 | "one": 1, 24 | "space": " ", 25 | "quote": "\"", 26 | "backslash": "\\", 27 | "controls": "\b\f\n\r\t", 28 | "slash": "/ & \/", 29 | "alpha": "abcdefghijklmnopqrstuvwyz", 30 | "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", 31 | "digit": "0123456789", 32 | "special": "`1~!@#$%^&*()_+-={':[,]}|;.?", 33 | "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", 34 | "true": true, 35 | "false": false, 36 | "null": null, 37 | "array":[ ], 38 | "object":{ }, 39 | "address": "50 St. James Street", 40 | "url": "http://www.JSON.org/", 41 | "comment": "// /* */": " ", 43 | " s p a c e d " :[1,2 , 3 44 | 45 | , 46 | 47 | 4 , 5 , 6 ,7 ],"compact": [1,2,3,4,5,6,7], 48 | "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", 49 | "quotes": "" \u0022 %22 0x22 034 "", 50 | "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?" 51 | : "A key can be any string" 52 | }, 53 | 0.5 ,98.6 54 | , 55 | 99.44 56 | , 57 | 58 | 1066, 59 | 1e1, 60 | 0.1e1, 61 | 1e-1, 62 | 1e00,2e+00,2e-00 63 | ,"rosebud"] 64 | ''' 65 | 66 | class TestPass1(TestCase): 67 | def test_parse(self): 68 | # test in/out equivalence and parsing 69 | res = json.loads(JSON) 70 | out = json.dumpsJSON(res) 71 | self.assertEqual(res, json.loads(out)) 72 | -------------------------------------------------------------------------------- /hjson/tests/test_pass2.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | import hjson as json 3 | 4 | # from http://json.org/JSON_checker/test/pass2.json 5 | JSON = r''' 6 | [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]] 7 | ''' 8 | 9 | class TestPass2(TestCase): 10 | def test_parse(self): 11 | # test in/out equivalence and parsing 12 | res = json.loads(JSON) 13 | out = json.dumpsJSON(res) 14 | self.assertEqual(res, json.loads(out)) 15 | -------------------------------------------------------------------------------- /hjson/tests/test_pass3.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | # from http://json.org/JSON_checker/test/pass3.json 6 | JSON = r''' 7 | { 8 | "JSON Test Pattern pass3": { 9 | "The outermost value": "must be an object or array.", 10 | "In this test": "It is an object." 11 | } 12 | } 13 | ''' 14 | 15 | class TestPass3(TestCase): 16 | def test_parse(self): 17 | # test in/out equivalence and parsing 18 | res = json.loads(JSON) 19 | out = json.dumpsJSON(res) 20 | self.assertEqual(res, json.loads(out)) 21 | -------------------------------------------------------------------------------- /hjson/tests/test_recursion.py: -------------------------------------------------------------------------------- 1 | from unittest import TestCase 2 | 3 | import hjson as json 4 | 5 | class JSONTestObject: 6 | pass 7 | 8 | 9 | class RecursiveJSONEncoder(json.JSONEncoder): 10 | recurse = False 11 | def default(self, o): 12 | if o is JSONTestObject: 13 | if self.recurse: 14 | return [JSONTestObject] 15 | else: 16 | return 'JSONTestObject' 17 | return json.JSONEncoder.default(o) 18 | 19 | 20 | class TestRecursion(TestCase): 21 | def test_listrecursion(self): 22 | x = [] 23 | x.append(x) 24 | try: 25 | json.dumpsJSON(x) 26 | except ValueError: 27 | pass 28 | else: 29 | self.fail("didn't raise ValueError on list recursion") 30 | x = [] 31 | y = [x] 32 | x.append(y) 33 | try: 34 | json.dumpsJSON(x) 35 | except ValueError: 36 | pass 37 | else: 38 | self.fail("didn't raise ValueError on alternating list recursion") 39 | y = [] 40 | x = [y, y] 41 | # ensure that the marker is cleared 42 | json.dumpsJSON(x) 43 | 44 | def test_dictrecursion(self): 45 | x = {} 46 | x["test"] = x 47 | try: 48 | json.dumpsJSON(x) 49 | except ValueError: 50 | pass 51 | else: 52 | self.fail("didn't raise ValueError on dict recursion") 53 | x = {} 54 | y = {"a": x, "b": x} 55 | # ensure that the marker is cleared 56 | json.dumpsJSON(y) 57 | 58 | def test_defaultrecursion(self): 59 | enc = RecursiveJSONEncoder() 60 | self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"') 61 | enc.recurse = True 62 | try: 63 | enc.encode(JSONTestObject) 64 | except ValueError: 65 | pass 66 | else: 67 | self.fail("didn't raise ValueError on default recursion") 68 | -------------------------------------------------------------------------------- /hjson/tests/test_scanstring.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from unittest import TestCase 3 | 4 | import hjson as json 5 | import hjson.decoder 6 | from hjson.compat import b, PY3 7 | 8 | class TestScanString(TestCase): 9 | # The bytes type is intentionally not used in most of these tests 10 | # under Python 3 because the decoder immediately coerces to str before 11 | # calling scanstring. In Python 2 we are testing the code paths 12 | # for both unicode and str. 13 | # 14 | # The reason this is done is because Python 3 would require 15 | # entirely different code paths for parsing bytes and str. 16 | # 17 | def test_py_scanstring(self): 18 | self._test_scanstring(hjson.decoder.scanstring) 19 | 20 | def _test_scanstring(self, scanstring): 21 | if sys.maxunicode == 65535: 22 | self.assertEqual( 23 | scanstring(u'"z\U0001d120x"', 1, None, True), 24 | (u'z\U0001d120x', 6)) 25 | else: 26 | self.assertEqual( 27 | scanstring(u'"z\U0001d120x"', 1, None, True), 28 | (u'z\U0001d120x', 5)) 29 | 30 | self.assertEqual( 31 | scanstring('"\\u007b"', 1, None, True), 32 | (u'{', 8)) 33 | 34 | self.assertEqual( 35 | scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True), 36 | (u'A JSON payload should be an object or array, not a string.', 60)) 37 | 38 | self.assertEqual( 39 | scanstring('["Unclosed array"', 2, None, True), 40 | (u'Unclosed array', 17)) 41 | 42 | self.assertEqual( 43 | scanstring('["extra comma",]', 2, None, True), 44 | (u'extra comma', 14)) 45 | 46 | self.assertEqual( 47 | scanstring('["double extra comma",,]', 2, None, True), 48 | (u'double extra comma', 21)) 49 | 50 | self.assertEqual( 51 | scanstring('["Comma after the close"],', 2, None, True), 52 | (u'Comma after the close', 24)) 53 | 54 | self.assertEqual( 55 | scanstring('["Extra close"]]', 2, None, True), 56 | (u'Extra close', 14)) 57 | 58 | self.assertEqual( 59 | scanstring('{"Extra comma": true,}', 2, None, True), 60 | (u'Extra comma', 14)) 61 | 62 | self.assertEqual( 63 | scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True), 64 | (u'Extra value after close', 26)) 65 | 66 | self.assertEqual( 67 | scanstring('{"Illegal expression": 1 + 2}', 2, None, True), 68 | (u'Illegal expression', 21)) 69 | 70 | self.assertEqual( 71 | scanstring('{"Illegal invocation": alert()}', 2, None, True), 72 | (u'Illegal invocation', 21)) 73 | 74 | self.assertEqual( 75 | scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True), 76 | (u'Numbers cannot have leading zeroes', 37)) 77 | 78 | self.assertEqual( 79 | scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True), 80 | (u'Numbers cannot be hex', 24)) 81 | 82 | self.assertEqual( 83 | scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True), 84 | (u'Too deep', 30)) 85 | 86 | self.assertEqual( 87 | scanstring('{"Missing colon" null}', 2, None, True), 88 | (u'Missing colon', 16)) 89 | 90 | self.assertEqual( 91 | scanstring('{"Double colon":: null}', 2, None, True), 92 | (u'Double colon', 15)) 93 | 94 | self.assertEqual( 95 | scanstring('{"Comma instead of colon", null}', 2, None, True), 96 | (u'Comma instead of colon', 25)) 97 | 98 | self.assertEqual( 99 | scanstring('["Colon instead of comma": false]', 2, None, True), 100 | (u'Colon instead of comma', 25)) 101 | 102 | self.assertEqual( 103 | scanstring('["Bad value", truth]', 2, None, True), 104 | (u'Bad value', 12)) 105 | 106 | for c in map(chr, range(0x00, 0x1f)): 107 | self.assertEqual( 108 | scanstring(c + '"', 0, None, False), 109 | (c, 2)) 110 | self.assertRaises( 111 | ValueError, 112 | scanstring, c + '"', 0, None, True) 113 | 114 | def test_issue3623(self): 115 | self.assertRaises(ValueError, json.decoder.scanstring, "xxx", 1, 116 | "xxx") 117 | self.assertRaises(UnicodeDecodeError, 118 | json.encoder.encode_basestring_ascii, b("xx\xff")) 119 | 120 | def test_surrogates(self): 121 | scanstring = json.decoder.scanstring 122 | 123 | def assertScan(given, expect, test_utf8=True): 124 | givens = [given] 125 | if not PY3 and test_utf8: 126 | givens.append(given.encode('utf8')) 127 | for given in givens: 128 | (res, count) = scanstring(given, 1, None, True) 129 | self.assertEqual(len(given), count) 130 | self.assertEqual(res, expect) 131 | 132 | assertScan( 133 | u'"z\\ud834\\u0079x"', 134 | u'z\ud834yx') 135 | assertScan( 136 | u'"z\\ud834\\udd20x"', 137 | u'z\U0001d120x') 138 | assertScan( 139 | u'"z\\ud834\\ud834\\udd20x"', 140 | u'z\ud834\U0001d120x') 141 | assertScan( 142 | u'"z\\ud834x"', 143 | u'z\ud834x') 144 | assertScan( 145 | u'"z\\udd20x"', 146 | u'z\udd20x') 147 | assertScan( 148 | u'"z\ud834x"', 149 | u'z\ud834x') 150 | # It may look strange to join strings together, but Python is drunk. 151 | # https://gist.github.com/etrepum/5538443 152 | assertScan( 153 | u'"z\\ud834\udd20x12345"', 154 | u''.join([u'z\ud834', u'\udd20x12345'])) 155 | assertScan( 156 | u'"z\ud834\\udd20x"', 157 | u''.join([u'z\ud834', u'\udd20x'])) 158 | # these have different behavior given UTF8 input, because the surrogate 159 | # pair may be joined (in maxunicode > 65535 builds) 160 | assertScan( 161 | u''.join([u'"z\ud834', u'\udd20x"']), 162 | u''.join([u'z\ud834', u'\udd20x']), 163 | test_utf8=False) 164 | 165 | self.assertRaises(ValueError, 166 | scanstring, u'"z\\ud83x"', 1, None, True) 167 | self.assertRaises(ValueError, 168 | scanstring, u'"z\\ud834\\udd2x"', 1, None, True) 169 | -------------------------------------------------------------------------------- /hjson/tests/test_separators.py: -------------------------------------------------------------------------------- 1 | import textwrap 2 | from unittest import TestCase 3 | 4 | import hjson as json 5 | 6 | 7 | class TestSeparators(TestCase): 8 | def test_separators(self): 9 | h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', 10 | {'nifty': 87}, {'field': 'yes', 'morefield': False} ] 11 | 12 | expect = textwrap.dedent("""\ 13 | [ 14 | [ 15 | "blorpie" 16 | ] , 17 | [ 18 | "whoops" 19 | ] , 20 | [] , 21 | "d-shtaeou" , 22 | "d-nthiouh" , 23 | "i-vhbjkhnth" , 24 | { 25 | "nifty" : 87 26 | } , 27 | { 28 | "field" : "yes" , 29 | "morefield" : false 30 | } 31 | ]""") 32 | 33 | 34 | d1 = json.dumpsJSON(h) 35 | d2 = json.dumpsJSON(h, indent=' ', sort_keys=True, separators=(' ,', ' : ')) 36 | 37 | h1 = json.loads(d1) 38 | h2 = json.loads(d2) 39 | 40 | self.assertEqual(h1, h) 41 | self.assertEqual(h2, h) 42 | self.assertEqual(d2, expect) 43 | -------------------------------------------------------------------------------- /hjson/tests/test_tool.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | import os 3 | import sys 4 | import textwrap 5 | import unittest 6 | import subprocess 7 | import tempfile 8 | try: 9 | # Python 3.x 10 | from test.support import strip_python_stderr 11 | except ImportError: 12 | # Python 2.6+ 13 | try: 14 | from test.test_support import strip_python_stderr 15 | except ImportError: 16 | # Python 2.5 17 | import re 18 | def strip_python_stderr(stderr): 19 | return re.sub( 20 | r"\[\d+ refs\]\r?\n?$".encode(), 21 | "".encode(), 22 | stderr).strip() 23 | 24 | class TestTool(unittest.TestCase): 25 | data = """ 26 | 27 | [["blorpie"],[ "whoops" ] , [ 28 | ],\t"d-shtaeou",\r"d-nthiouh", 29 | "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field" 30 | :"yes"} ] 31 | """ 32 | 33 | expect = textwrap.dedent("""\ 34 | [ 35 | [ 36 | blorpie 37 | ] 38 | [ 39 | whoops 40 | ] 41 | [] 42 | d-shtaeou 43 | d-nthiouh 44 | i-vhbjkhnth 45 | { 46 | nifty: 87 47 | } 48 | { 49 | morefield: false 50 | field: yes 51 | } 52 | ] 53 | """) 54 | 55 | def runTool(self, args=None, data=None): 56 | argv = [sys.executable, '-m', 'hjson.tool'] 57 | if args: 58 | argv.extend(args) 59 | proc = subprocess.Popen(argv, 60 | stdin=subprocess.PIPE, 61 | stderr=subprocess.PIPE, 62 | stdout=subprocess.PIPE) 63 | out, err = proc.communicate(data) 64 | self.assertEqual(strip_python_stderr(err), ''.encode()) 65 | self.assertEqual(proc.returncode, 0) 66 | return out 67 | 68 | def test_stdin_stdout(self): 69 | self.assertEqual( 70 | self.runTool(data=self.data.encode()), 71 | self.expect.encode()) 72 | 73 | def test_infile_stdout(self): 74 | with tempfile.NamedTemporaryFile() as infile: 75 | infile.write(self.data.encode()) 76 | infile.flush() 77 | self.assertEqual( 78 | self.runTool(args=[infile.name]), 79 | self.expect.encode()) 80 | 81 | def x_test_infile_outfile(self): 82 | """Not currently an option in tool""" 83 | with tempfile.NamedTemporaryFile() as infile: 84 | infile.write(self.data.encode()) 85 | infile.flush() 86 | # outfile will get overwritten by tool, so the delete 87 | # may not work on some platforms. Do it manually. 88 | outfile = tempfile.NamedTemporaryFile() 89 | try: 90 | self.assertEqual( 91 | self.runTool(args=[infile.name, outfile.name]), 92 | ''.encode()) 93 | with open(outfile.name, 'rb') as f: 94 | self.assertEqual(f.read(), self.expect.encode()) 95 | finally: 96 | outfile.close() 97 | if os.path.exists(outfile.name): 98 | os.unlink(outfile.name) 99 | -------------------------------------------------------------------------------- /hjson/tests/test_tuple.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from hjson.compat import StringIO 4 | import hjson as json 5 | 6 | class TestTuples(unittest.TestCase): 7 | def test_tuple_array_dumps(self): 8 | t = (1, 2, 3) 9 | expect = json.dumpsJSON(list(t)) 10 | # Default is True 11 | self.assertEqual(expect, json.dumpsJSON(t)) 12 | self.assertEqual(expect, json.dumpsJSON(t, tuple_as_array=True)) 13 | self.assertRaises(TypeError, json.dumpsJSON, t, tuple_as_array=False) 14 | # Ensure that the "default" does not get called 15 | self.assertEqual(expect, json.dumpsJSON(t, default=repr)) 16 | self.assertEqual(expect, json.dumpsJSON(t, tuple_as_array=True, 17 | default=repr)) 18 | # Ensure that the "default" gets called 19 | self.assertEqual( 20 | json.dumpsJSON(repr(t)), 21 | json.dumpsJSON(t, tuple_as_array=False, default=repr)) 22 | 23 | def test_tuple_array_dump(self): 24 | t = (1, 2, 3) 25 | expect = json.dumpsJSON(list(t)) 26 | # Default is True 27 | sio = StringIO() 28 | json.dumpJSON(t, sio) 29 | self.assertEqual(expect, sio.getvalue()) 30 | sio = StringIO() 31 | json.dumpJSON(t, sio, tuple_as_array=True) 32 | self.assertEqual(expect, sio.getvalue()) 33 | self.assertRaises(TypeError, json.dumpJSON, t, StringIO(), 34 | tuple_as_array=False) 35 | # Ensure that the "default" does not get called 36 | sio = StringIO() 37 | json.dumpJSON(t, sio, default=repr) 38 | self.assertEqual(expect, sio.getvalue()) 39 | sio = StringIO() 40 | json.dumpJSON(t, sio, tuple_as_array=True, default=repr) 41 | self.assertEqual(expect, sio.getvalue()) 42 | # Ensure that the "default" gets called 43 | sio = StringIO() 44 | json.dumpJSON(t, sio, tuple_as_array=False, default=repr) 45 | self.assertEqual( 46 | json.dumpsJSON(repr(t)), 47 | sio.getvalue()) 48 | 49 | class TestNamedTuple(unittest.TestCase): 50 | def test_namedtuple_dump(self): 51 | pass 52 | -------------------------------------------------------------------------------- /hjson/tests/test_unicode.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import codecs 3 | from unittest import TestCase 4 | 5 | import hjson as json 6 | from hjson.compat import unichr, text_type, b, u, BytesIO 7 | 8 | class TestUnicode(TestCase): 9 | def test_encoding1(self): 10 | encoder = json.JSONEncoder(encoding='utf-8') 11 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 12 | s = u.encode('utf-8') 13 | ju = encoder.encode(u) 14 | js = encoder.encode(s) 15 | self.assertEqual(ju, js) 16 | 17 | def test_encoding2(self): 18 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 19 | s = u.encode('utf-8') 20 | ju = json.dumpsJSON(u, encoding='utf-8') 21 | js = json.dumpsJSON(s, encoding='utf-8') 22 | self.assertEqual(ju, js) 23 | 24 | def test_encoding3(self): 25 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 26 | j = json.dumpsJSON(u) 27 | self.assertEqual(j, '"\\u03b1\\u03a9"') 28 | 29 | def test_encoding4(self): 30 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 31 | j = json.dumpsJSON([u]) 32 | self.assertEqual(j, '["\\u03b1\\u03a9"]') 33 | 34 | def test_encoding5(self): 35 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 36 | j = json.dumpsJSON(u, ensure_ascii=False) 37 | self.assertEqual(j, u'"' + u + u'"') 38 | 39 | def test_encoding6(self): 40 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 41 | j = json.dumpsJSON([u], ensure_ascii=False) 42 | self.assertEqual(j, u'["' + u + u'"]') 43 | 44 | def test_big_unicode_encode(self): 45 | u = u'\U0001d120' 46 | self.assertEqual(json.dumpsJSON(u), '"\\ud834\\udd20"') 47 | self.assertEqual(json.dumpsJSON(u, ensure_ascii=False), u'"\U0001d120"') 48 | 49 | def test_big_unicode_decode(self): 50 | u = u'z\U0001d120x' 51 | self.assertEqual(json.loads('"' + u + '"'), u) 52 | self.assertEqual(json.loads('"z\\ud834\\udd20x"'), u) 53 | 54 | def test_unicode_decode(self): 55 | for i in range(0, 0xd7ff): 56 | u = unichr(i) 57 | #s = '"\\u{0:04x}"'.format(i) 58 | s = '"\\u%04x"' % (i,) 59 | self.assertEqual(json.loads(s), u) 60 | 61 | def test_object_pairs_hook_with_unicode(self): 62 | s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' 63 | p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4), 64 | (u"qrt", 5), (u"pad", 6), (u"hoy", 7)] 65 | self.assertEqual(json.loads(s), eval(s)) 66 | self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p) 67 | od = json.loads(s, object_pairs_hook=json.OrderedDict) 68 | self.assertEqual(od, json.OrderedDict(p)) 69 | self.assertEqual(type(od), json.OrderedDict) 70 | # the object_pairs_hook takes priority over the object_hook 71 | self.assertEqual(json.loads(s, 72 | object_pairs_hook=json.OrderedDict, 73 | object_hook=lambda x: None), 74 | json.OrderedDict(p)) 75 | 76 | 77 | def test_default_encoding(self): 78 | self.assertEqual(json.loads(u'{"a": "\xe9"}'.encode('utf-8')), 79 | {'a': u'\xe9'}) 80 | 81 | def test_unicode_preservation(self): 82 | self.assertEqual(type(json.loads(u'""')), text_type) 83 | self.assertEqual(type(json.loads(u'"a"')), text_type) 84 | self.assertEqual(type(json.loads(u'["a"]')[0]), text_type) 85 | 86 | def test_ensure_ascii_false_returns_unicode(self): 87 | # http://code.google.com/p/simplejson/issues/detail?id=48 88 | self.assertEqual(type(json.dumpsJSON([], ensure_ascii=False)), text_type) 89 | self.assertEqual(type(json.dumpsJSON(0, ensure_ascii=False)), text_type) 90 | self.assertEqual(type(json.dumpsJSON({}, ensure_ascii=False)), text_type) 91 | self.assertEqual(type(json.dumpsJSON("", ensure_ascii=False)), text_type) 92 | 93 | def test_ensure_ascii_false_bytestring_encoding(self): 94 | # http://code.google.com/p/simplejson/issues/detail?id=48 95 | doc1 = {u'quux': b('Arr\xc3\xaat sur images')} 96 | doc2 = {u'quux': u('Arr\xeat sur images')} 97 | doc_ascii = '{"quux": "Arr\\u00eat sur images"}' 98 | doc_unicode = u'{"quux": "Arr\xeat sur images"}' 99 | self.assertEqual(json.dumpsJSON(doc1), doc_ascii) 100 | self.assertEqual(json.dumpsJSON(doc2), doc_ascii) 101 | self.assertEqual(json.dumpsJSON(doc1, ensure_ascii=False), doc_unicode) 102 | self.assertEqual(json.dumpsJSON(doc2, ensure_ascii=False), doc_unicode) 103 | 104 | def test_ensure_ascii_linebreak_encoding(self): 105 | # http://timelessrepo.com/json-isnt-a-javascript-subset 106 | s1 = u'\u2029\u2028' 107 | s2 = s1.encode('utf8') 108 | expect = '"\\u2029\\u2028"' 109 | self.assertEqual(json.dumpsJSON(s1), expect) 110 | self.assertEqual(json.dumpsJSON(s2), expect) 111 | self.assertEqual(json.dumpsJSON(s1, ensure_ascii=False), expect) 112 | self.assertEqual(json.dumpsJSON(s2, ensure_ascii=False), expect) 113 | 114 | def test_invalid_escape_sequences(self): 115 | # incomplete escape sequence 116 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u') 117 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u1') 118 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u12') 119 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u123') 120 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u1234') 121 | # invalid escape sequence 122 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u123x"') 123 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u12x4"') 124 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\u1x34"') 125 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ux234"') 126 | if sys.maxunicode > 65535: 127 | # invalid escape sequence for low surrogate 128 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u"') 129 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u0"') 130 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u00"') 131 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u000"') 132 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u000x"') 133 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u00x0"') 134 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\u0x00"') 135 | self.assertRaises(json.HjsonDecodeError, json.loads, '"\\ud800\\ux000"') 136 | 137 | def test_ensure_ascii_still_works(self): 138 | # in the ascii range, ensure that everything is the same 139 | for c in map(unichr, range(0, 127)): 140 | self.assertEqual( 141 | json.dumpsJSON(c, ensure_ascii=False), 142 | json.dumpsJSON(c)) 143 | snowman = u'\N{SNOWMAN}' 144 | self.assertEqual( 145 | json.dumpsJSON(c, ensure_ascii=False), 146 | '"' + c + '"') 147 | 148 | def test_strip_bom(self): 149 | content = u"\u3053\u3093\u306b\u3061\u308f" 150 | json_doc = codecs.BOM_UTF8 + b(json.dumpsJSON(content)) 151 | self.assertEqual(json.load(BytesIO(json_doc)), content) 152 | for doc in json_doc, json_doc.decode('utf8'): 153 | self.assertEqual(json.loads(doc), content) 154 | -------------------------------------------------------------------------------- /hjson/tool.py: -------------------------------------------------------------------------------- 1 | r"""Command-line tool to validate and pretty-print JSON 2 | 3 | Usage:: 4 | 5 | $ echo '{"json":"obj"}' | hjson 6 | { 7 | "json": "obj" 8 | } 9 | 10 | """ 11 | from __future__ import with_statement 12 | import sys 13 | import hjson 14 | 15 | HELP="""Hjson, a user interface for JSON 16 | 17 | Usage: 18 | hjson [options] 19 | hjson [options] 20 | hjson (-h | --help) 21 | hjson (-V | --version) 22 | 23 | Options: 24 | -h --help Show this screen. 25 | -j Output as formatted JSON. 26 | -c Output as JSON. 27 | -V --version Show version. 28 | """; 29 | 30 | def showerr(msg): 31 | sys.stderr.write(msg) 32 | sys.stderr.write("\n") 33 | 34 | def main(): 35 | format = 'hjson' 36 | args = [] 37 | for arg in sys.argv[1:]: 38 | if arg == '-h' or arg == '--help': 39 | showerr(HELP) 40 | return 41 | elif arg == '-j': format = 'json' 42 | elif arg == '-c': format = 'compact' 43 | elif arg == '-V' or arg == '--version': 44 | showerr('Hjson ' + hjson.__version__) 45 | return 46 | 47 | elif arg[0] == '-': 48 | showerr(HELP) 49 | raise SystemExit('unknown option ' + arg) 50 | else: 51 | args.append(arg) 52 | 53 | outfile = sys.stdout 54 | if len(args) == 0: 55 | infile = sys.stdin 56 | elif len(args) == 1: 57 | infile = open(args[0], 'r') 58 | else: 59 | showerr(HELP) 60 | raise SystemExit('unknown options') 61 | 62 | with infile: 63 | try: 64 | obj = hjson.load(infile, use_decimal=True) 65 | except ValueError: 66 | raise SystemExit(sys.exc_info()[1]) 67 | 68 | with outfile: 69 | if format == 'json': 70 | hjson.dumpJSON(obj, outfile, ensure_ascii=False, use_decimal=True, indent=' ') 71 | elif format == 'compact': 72 | hjson.dumpJSON(obj, outfile, ensure_ascii=False, use_decimal=True, separators=(',', ':')) 73 | else: 74 | hjson.dump(obj, outfile, ensure_ascii=False, use_decimal=True) 75 | 76 | outfile.write('\n') 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import with_statement 3 | 4 | import sys 5 | try: 6 | from setuptools import setup, Command 7 | except ImportError: 8 | from distutils.core import setup, Command 9 | from distutils.errors import CCompilerError, DistutilsExecError, \ 10 | DistutilsPlatformError 11 | 12 | IS_PYPY = hasattr(sys, 'pypy_translation_info') 13 | VERSION = '3.1.0' 14 | DESCRIPTION = "Hjson, a user interface for JSON." 15 | 16 | with open('README.rst', 'r') as f: 17 | LONG_DESCRIPTION = f.read() 18 | 19 | CLASSIFIERS = filter(None, map(str.strip, 20 | """ 21 | Development Status :: 5 - Production/Stable 22 | Intended Audience :: Developers 23 | License :: OSI Approved :: MIT License 24 | License :: OSI Approved :: Academic Free License (AFL) 25 | Programming Language :: Python 26 | Programming Language :: Python :: 2 27 | Programming Language :: Python :: 2.6 28 | Programming Language :: Python :: 2.7 29 | Programming Language :: Python :: 3 30 | Programming Language :: Python :: 3.3 31 | Programming Language :: Python :: 3.4 32 | Programming Language :: Python :: 3.5 33 | Programming Language :: Python :: Implementation :: CPython 34 | Programming Language :: Python :: Implementation :: PyPy 35 | Topic :: Software Development :: Libraries :: Python Modules 36 | """.splitlines())) 37 | 38 | class BuildFailed(Exception): 39 | pass 40 | 41 | class TestCommand(Command): 42 | user_options = [] 43 | 44 | def initialize_options(self): 45 | pass 46 | 47 | def finalize_options(self): 48 | pass 49 | 50 | def run(self): 51 | import sys, subprocess 52 | raise SystemExit( 53 | subprocess.call([sys.executable, 54 | # Turn on deprecation warnings 55 | '-Wd', 56 | 'hjson/tests/__init__.py'])) 57 | 58 | def run_setup(): 59 | cmdclass = dict(test=TestCommand) 60 | kw = dict(cmdclass=cmdclass) 61 | 62 | setup( 63 | name="hjson", 64 | version=VERSION, 65 | description=DESCRIPTION, 66 | long_description=LONG_DESCRIPTION, 67 | keywords="json comments configuration", 68 | classifiers=CLASSIFIERS, 69 | author="Christian Zangl", 70 | author_email="laktak@cdak.net", 71 | url="http://github.com/hjson/hjson-py", 72 | license="MIT License", 73 | packages=['hjson', 'hjson.tests'], 74 | platforms=['any'], 75 | entry_points={ 76 | "console_scripts": [ 77 | "hjson = hjson.tool:main", 78 | ], 79 | }, 80 | **kw, 81 | ) 82 | 83 | run_setup() 84 | --------------------------------------------------------------------------------