commentjson is a Python package that enables you to include Python-style (#) and JavaScript-style (//) comments within your JSON files. Its API closely mirrors the standard library's `json` module, providing `load`, `loads`, `dump`, and `dumps` functionalities. Currently at version 0.9.0, the library is actively maintained, with recent releases focusing on performance improvements and compatibility.
pip install commentjsonVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse a JSON string containing both Python-style `#` and JavaScript-style `//` comments using `commentjson.loads`. It then shows how to serialize a Python dictionary back into a JSON string using `commentjson.dumps`, which behaves like the standard `json` module, meaning comments are typically discarded during serialization. The API is designed to be a drop-in replacement for the standard `json` library.
Upgrade to Python 2.7 or, preferably, Python 3 for compatibility.
Ensure `commentjson` and `lark` are updated to their latest compatible versions. If issues persist, consider pinning `lark` to a known working version as specified by `commentjson`'s `requirements.txt` on GitHub.
Understand that `commentjson` is for *reading* commented JSON. If comments need to be preserved across read/modify/write cycles, you would need a more sophisticated solution or a different configuration format like YAML or JSONC, or manually manage comments (which `commentjson` does not support for round-tripping comments).
Upgrade to version 0.8.2 or newer to ensure consistent and correct unicode handling.
Upgrade to version 0.9.0 or newer to use trailing commas. Remember that this is still non-standard JSON, only supported by `commentjson`.
Use `commentjson.load` or `commentjson.loads` instead of `json.load` or `json.loads` to correctly parse the JSON with comments. Example: `import commentjson; data = commentjson.loads(commented_json_string)`
Import `commentjson` as a module and then access its methods. Example: `import commentjson; commentjson.dump(obj, fp)` or `commentjson.loads(text)`
Examine the JSON content *after* comments have been removed to identify and fix any remaining syntax errors. The error message within `JSONLibraryException` provides details from the standard `json` module about the specific parsing issue and location.