CommentJSON
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.
Warnings
- breaking Python 2.6 support was officially dropped in version 0.8.0. Applications targeting Python 2.6 will not be compatible with this or newer versions.
- gotcha commentjson relies on the `lark` parser. Earlier versions (0.8.1, 0.8.3) experienced compatibility issues with specific `lark-parser` releases. While generally resolved, ensure your `lark` dependency is compatible if you encounter parsing errors after updates.
- gotcha Standard JSON (per RFC 8259) does not officially support comments. Using `commentjson` allows you to *parse* JSON files with comments, but if you `dump` or `dumps` the data, the comments will be lost. Any other standard JSON parser will fail if fed a file containing comments.
- gotcha Version 0.8.2 fixed unicode handling issues to align with the standard `json` package. Older versions might have subtle differences in how unicode characters are processed.
- gotcha Prior to v0.9.0, trailing commas in JSON were not officially supported and would cause parsing errors. While v0.9.0 added support, be aware that standard JSON does not permit trailing commas, so other parsers will still fail.
Install
-
pip install commentjson
Imports
- commentjson
import commentjson
Quickstart
import commentjson
import os
# Example JSON string with comments
json_string_with_comments = '''{
"name": "Vaidik Kapoor", # Person's name
"location": "Delhi, India", // Person's location
# Section contains info about
// person's appearance
"appearance": {
"hair_color": "black",
"eyes_color": "black",
"height": "6"
}
}'''
# Deserialize JSON with comments
data = commentjson.loads(json_string_with_comments)
print(f"Loaded data: {data}")
# Serialize Python object back to JSON (comments are not preserved by default in dumps/dump)
# To demonstrate, let's modify and dump
data['appearance']['height'] = '6 ft'
output_json = commentjson.dumps(data, indent=4)
print(f"\nSerialized data (without original comments):\n{output_json}")
# If you were to load from a file, you'd use commentjson.load
# with open('config.jsonc', 'w') as f:
# f.write(json_string_with_comments)
# with open('config.jsonc', 'r') as f:
# file_data = commentjson.load(f)
# print(f"\nLoaded from file: {file_data}")