CommentJSON

0.9.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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.

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}")

view raw JSON →