jsonc-document¶
A typed JSONC parser that preserves comments, tokens, and source spans. It requires Python 3.12 or newer and has no runtime dependencies.
Installation¶
pip install jsonc-document
Usage¶
"""Parse JSONC while preserving source comments."""
import jsonc_document
source = '// heading\n{"count": 2}'
document = jsonc_document.parse(source=source)
assert document.value == {"count": 2}
assert document.comments[0].text == "// heading"
assert document.to_source() == source
Use loads(source=...) when only Python values are needed.
See the documentation for the full API and parsing policies.
API reference¶
Typed JSONC parsing with comments and original source spans.
- class jsonc_document.Document(source: str, root: Node, tokens: tuple[Token, ...])¶
A parsed JSONC source snapshot with every lexical token retained.
Mutating a returned Python collection does not rewrite source text. Source editing is outside the document API.
- class jsonc_document.ErrorKind(*values)¶
Structured error categories for applications adapting diagnostics.
- DEPTH = 5¶
- DUPLICATE_KEY = 2¶
- INTEGER_DIGITS = 4¶
- NUMBER_RANGE = 3¶
- SYNTAX = 1¶
- exception jsonc_document.JSONCDecodeError(*, message: str, source: str, position: int, reason: ErrorKind)¶
A syntax or data-policy error with original source coordinates.
posis a zero-based character offset.linenoandcolnoare one-based and recognize CR, LF, and CRLF.
- class jsonc_document.Node(value: Value, start: int, end: int, children: tuple[Node, ...], keys: tuple[Token, ...], commas: tuple[Token, ...])¶
A value and its syntax tree, retaining object keys in source order.
childrencontains array elements or object member values.keysis empty for arrays and scalars. Collection delimiters are included in the node’s half-open source span.
- class jsonc_document.Token(kind: TokenKind, text: str, start: int, end: int, value: Scalar)¶
A token’s original spelling and half-open Unicode source span.
- class jsonc_document.TokenKind(*values)¶
The lexical categories retained in a document.
- COMMENT = 5¶
- LITERAL = 3¶
- NUMBER = 4¶
- PUNCTUATION = 1¶
- STRING = 2¶
- WHITESPACE = 6¶
- jsonc_document.parse(*, source: str) Document¶
Parse a JSONC document, retaining tokens, comments, and source spans.
Duplicate keys and finite numbers outside binary64 range are rejected. Up to 512 nested collections are accepted. No source is executed.
- jsonc_document.tokenize(*, source: str) Iterator[Token]¶
Yield every source token, including comments and whitespace.
Lexical validity is checked; use
parseto validate the complete document grammar.
Public recursive types for decoded JSONC values.