jsonc-edit
A Python interface to Microsoft's jsonc-parser, designed for source-preserving JSONC edits.
What it is
jsonc-edit is a lightweight Python package that provides surgical source-editing capabilities for JSONC (JSON with Comments) files. Instead of providing standard JSON parsing and dumping, it wraps Microsoft's world-class AST-aware jsonc-parser library under the hood, giving you exact, developer-grade source manipulation in Python.
Why it exists
When modifying configuration files (like tsconfig.json or .vscode/settings.json), the standard programmatic approach is highly destructive:
parse source string → modify Python dict in memory → dump back to string
This naive approach immediately strips all // line comments, /* block comments */, trailing commas, and completely mangles the developer's original indentation and formatting choices.
jsonc-edit uses a fundamentally different approach:
semantic JSONC edit → generate precise text offset edits → apply edits to raw string
By analyzing the AST and applying surgical character replacements, jsonc-edit perfectly preserves all human-authored elements in the file, including neighboring comments and specific array formatting.
Scope
jsonc-edit is intended to be a reusable, generalized JSONC source-editing library. It is strictly scoped to this purpose.
It is not:
- A
tsconfig.jsonmanager. - A framework-specific plugin or library.
- A full JSONC configuration framework that validates schemas or paths.
Installation
pip install jsonc-edit
Runtime Prerequisites
Because jsonc-edit leverages the official Microsoft parser to ensure exact semantic correctness, it runs a tiny invisible Node.js daemon under the hood to process the edits.
You must have node and npm installed and available on your system path.
During its first execution, jsonc-edit will automatically install the necessary pinned parser package into an isolated user-level cache (~/.jsonc-edit/versions/). It does not pollute your project's node_modules.
Windows users: jsonc-edit fully supports Windows. The runtime installer automatically routes npm through cmd.exe to work around Windows-specific batch file execution constraints.
Basic Example
from jsonc_edit import modify, apply_edits
source = """{
// My custom aliases
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}"""
# Generate the specific string manipulations needed
edits = modify(
source,
["compilerOptions", "paths", "@example"],
["./types.d.ts"],
)
# Apply them to the raw source code
result = apply_edits(source, edits)
print(result)
The output will safely insert the new alias while completely respecting the existing // My custom aliases comment and the surrounding whitespace preferences.
Important Semantics
Because jsonc-edit uses Microsoft's parser engine, you inherit its intelligent formatting behavior natively:
- Comments:
//and/* */comments anywhere in the file are perfectly preserved. - Trailing Commas: Existing trailing commas on unaffected properties remain untouched.
- Formatting: You can optionally pass
options={"formattingOptions": {"insertSpaces": True, "tabSize": 4}}tomodify()to ensure any newly scaffolded objects match your project's preferred spacing. - Existing Values: Modifying a deeply nested property that does not exist yet (e.g.,
["compilerOptions", "paths", "new"]on an empty{}file) will correctly and cleanly scaffold out the missingcompilerOptionsandpathsobjects for you. - Idempotency: Attempting to set an array or object that is already functionally identical may still result in edits if the underlying parser chooses to reformat the specific block to match uniform JSON spacing.
- Errors: Invalid operations or syntax crashes will natively bubble up into Python as a
JsoncParseError. Missing Node/NPM environments will raise aRuntimeBootstrapError.
Architecture
jsonc-edit uses a persistent, line-buffered Node.js daemon managed directly by Python. This means:
- It does not spawn a new Node process for every edit. It boots once.
- It communicates blisteringly fast via newline-delimited JSON over
stdin/stdout. - It cleanly shuts down alongside the Python interpreter via
atexithooks.
You do not need to manage this daemon yourself. It operates entirely transparently behind the modify and apply_edits functions. If you need explicit deterministic lifecycle management, a context manager is available:
from jsonc_edit import edit_session, modify
with edit_session():
edits = modify("{}", ["a"], 1)
API Reference
edit(text: str, path: List[str | int], value: Any, options=None) -> str
Generates edits for modifying the value at path to value and immediately applies them to text. Path segments are interpreted literally (no escaping needed).
edit_file(filepath: str | Path, path: List[str | int], value: Any, options=None) -> None
Safely reads filepath, applies the edit via edit(), and atomically writes back the modification only if the content actually changed.
edit_many(text: str, operations: List[Tuple[path, value]], options=None) -> str
Applies multiple operations sequentially without causing internal offset corruption.
get_value(text: str, path: List[str | int]) -> Any | MISSING
Semantically parses and returns the value at the target path. Returns the MISSING sentinel if the path does not exist, explicitly distinguishing from an actual "property": null assignment.
modify(text: str, path: List[str | int], value: Any, options=None) -> List[Edit]
Analyzes the AST and generates a precise list of raw offset character edits (without applying them).
apply_edits(text: str, edits: List[Edit]) -> str
Applies raw offset character edits to the source string.
edit_session()
A context manager that guarantees the background Node.js daemon shuts down perfectly when exiting the with block. Mostly useful for strict deterministic lifecycle scripts.
Metadata
Release files for jsonc-edit 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| jsonc_edit-0.2.1.tar.gz | 89.9 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| jsonc_edit-0.2.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 101.7 kB
Release files / jsonc_edit-0.2.1.tar.gz
| Download URL | jsonc_edit-0.2.1.tar.gz |
|---|---|
| Size | 89.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3bb5beb878cdeb3a21d5d9d70d9084fc8b34cc9c068ee0cd24dcc447cbdd6ac3
|
|
BLAKE2b-256 checksum How to use checksums |
f79faabef72fd23097d4d18cc97296123a1c49e92b1c656c42a4b66a361d18d0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / jsonc_edit-0.2.1-py3-none-any.whl
| Download URL | jsonc_edit-0.2.1-py3-none-any.whl |
|---|---|
| Size | 11.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1963b1efef1c2e6000e76baf8719b37375690f41ea6859803b0a51133f6135f6
|
|
BLAKE2b-256 checksum How to use checksums |
9706737345d3ddce6cc8b7b8d94e381756b920374771e3a2129208bc9156a0b7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for jsonc-edit 0.2.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.