demjson3
demjson3 is a Python 3 specific library for encoding, decoding, and validating JSON data, fully compliant with RFC 7159. It is a fork of the `demjson` project, updated to address Python 3 compatibility issues and provide enhanced error handling and linting capabilities. It offers both strict JSON parsing and a non-strict mode for more JavaScript-like syntax. The library is currently at version 3.0.6, with its last release in October 2022.
Warnings
- breaking Users migrating from the original `demjson` library to `demjson3` (especially in Python 3 environments) should update their `import` statements. `demjson3` is a dedicated Python 3 fork, resolving compatibility issues (`use_2to3` errors with newer `setuptools`) that plagued `demjson` in Python 3.
- gotcha `demjson3` defaults to strict RFC 7159 compliance. This means non-standard JavaScript syntax (e.g., comments, unquoted keys, single-quoted strings, hexadecimal numbers, `undefined` keyword) will raise errors during decoding.
- gotcha When implementing `json_equivalent()` on custom Python classes for encoding, this method must return standard Python objects (dictionaries, lists, primitives) that `demjson3` can then encode. It should *not* return an already JSON-formatted string, as this will lead to double-encoding or incorrect output.
- gotcha `demjson3` automatically converts numbers that would lose precision as standard Python `float` types into `decimal.Decimal` objects during decoding to preserve accuracy.
Install
-
pip install demjson3
Imports
- encode
import demjson json_string = demjson.encode(python_object)
import demjson3 json_string = demjson3.encode(python_object)
- decode
import demjson python_object = demjson.decode(json_string)
import demjson3 python_object = demjson3.decode(json_string)
Quickstart
import demjson3
# Encode Python data to JSON string
python_data = {'name': 'Alice', 'age': 30, 'isStudent': False, 'courses': ['Math', 'Science'], 'extra': None}
json_output = demjson3.encode(python_data, indent=2, strict=True)
print('Encoded JSON:')
print(json_output)
# Decode JSON string to Python data
json_input = '{"product": "Laptop", "price": 1200.50, "inStock": true}'
python_decoded = demjson3.decode(json_input)
print('\nDecoded Python data:')
print(python_decoded)
# Example of non-strict decoding (allowing comments and unquoted keys)
non_strict_json = "{ /* A comment */ myKey: 'value', another: undefined }"
python_non_strict = demjson3.decode(non_strict_json, strict=False)
print('\nDecoded non-strict JSON:')
print(python_non_strict)