What is jsonc-parser?
The jsonc-parser npm package is used for parsing and manipulating JSONC (JSON with Comments) files. It provides functionality to parse JSONC content, extract errors, and visit nodes within the JSONC structure. It also allows for modifications and formatting of the JSONC content.
What are jsonc-parser's main functionalities?
Parsing JSONC
This feature allows you to parse JSONC content, which includes comments, without stripping them out. It can handle both single-line and multi-line comments.
{"text": "// This is a comment\n{\"key\": \"value\"}"}
Extracting Errors
jsonc-parser can extract errors from JSONC content, which is useful for validating and providing feedback on the correctness of the JSONC.
{"text": "{\"key\": \"value\", // invalid comment\n}"}
Visiting Nodes
This feature allows you to visit nodes within the JSONC structure and perform operations or analysis on them, such as logging property names.
{"text": "{\"key\": {\"nestedKey\": \"nestedValue\"}}", "visitor": {"onObjectProperty": (property, visitContext) => { console.log(property); }}}
Modifying JSONC
jsonc-parser provides functionality to modify the JSONC content by specifying the path to the node and the new value.
{"text": "{\"key\": \"value\"}", "modifications": [{"path": [\"key\"], "value": \"newValue\"}]}
Formatting JSONC
This feature allows you to format JSONC content according to specified formatting options, such as using spaces or tabs for indentation.
{"text": "{\"key\":\"value\"}", "options": {"insertSpaces": true, "tabSize": 2}}
Other packages similar to jsonc-parser
strip-json-comments
This package is used to strip comments from JSON or JSONC content, allowing you to parse it with standard JSON parsers. It differs from jsonc-parser as it does not retain comments and does not provide functionality for visiting nodes or extracting errors.
comment-json
comment-json is similar to jsonc-parser in that it allows for parsing and stringifying JSONC. However, its API and feature set may differ, and it may not have the same focus on providing detailed error information or node visiting capabilities.
jsonc-parser
Scanner and parser for JSON with comments.
Why?
JSONC is JSON with JavaScript style comments. This node module provides a scanner and fault tolerant parser that can process JSONC but is also useful for standard JSON.
- the scanner tokenizes the input string into tokens and token offsets
- the visit function implements a 'SAX' style parser with callbacks for the encountered properties and values.
- the parseTree function computes a hierarchical DOM with offsets representing the encountered properties and values.
- the parse function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion.
- the getLocation API returns a location object that describes the property or value located at a given offset in a JSON document.
- the findNodeAtLocation API finds the node at a given location path in a JSON DOM.
- the format API computes edits to format a JSON document.
- the modify API computes edits to insert, remove or replace a property or value in a JSON document.
- the applyEdits API applies edits to a document.
Installation
npm install --save jsonc-parser
API
Scanner:
export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner;
export interface JSONScanner {
setPosition(pos: number): any;
scan(): SyntaxKind;
getPosition(): number;
getToken(): SyntaxKind;
getTokenValue(): string;
getTokenOffset(): number;
getTokenLength(): number;
getTokenStartLine(): number;
getTokenStartCharacter(): number;
getTokenError(): ScanError;
}
Parser:
export interface ParseOptions {
disallowComments?: boolean;
allowTrailingComma?: boolean;
allowEmptyContent?: boolean;
}
export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
export interface JSONVisitor {
onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;
}
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined;
export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";
export interface Node {
type: NodeType;
value?: any;
offset: number;
length: number;
colonOffset?: number;
parent?: Node;
children?: Node[];
}
Utilities:
export declare function stripComments(text: string, replaceCh?: string): string;
export declare function getLocation(text: string, position: number): Location;
export declare type Segment = string | number;
export declare type JSONPath = Segment[];
export interface Location {
previousNode?: Node;
path: JSONPath;
matches: (patterns: JSONPath) => boolean;
isAtPropertyKey: boolean;
}
export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined;
export function getNodePath(node: Node): JSONPath;
export function getNodeValue(node: Node): any;
export function format(documentText: string, range: Range, options: FormattingOptions): EditResult;
export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
export function applyEdits(text: string, edits: EditResult): string;
export type EditResult = Edit[];
export interface Edit {
offset: number;
length: number;
content: string;
}
export interface Range {
offset: number;
length: number;
}
export interface FormattingOptions {
tabSize: number;
insertSpaces: boolean;
eol: string;
}
export interface ModificationOptions {
formattingOptions?: FormattingOptions;
isArrayInsertion?: boolean;
getInsertionIndex?: (properties: string[]) => number;
}
License
(MIT License)
Copyright 2018, Microsoft