1 | # jsonc-parser
|
2 | Scanner and parser for JSON with comments.
|
3 |
|
4 | [![npm Package](https://img.shields.io/npm/v/jsonc-parser.svg?style=flat-square)](https://www.npmjs.org/package/jsonc-parser)
|
5 | [![NPM Downloads](https://img.shields.io/npm/dm/jsonc-parser.svg)](https://npmjs.org/package/jsonc-parser)
|
6 | [![Build Status](https://travis-ci.org/Microsoft/node-jsonc-parser.svg?branch=master)](https://travis-ci.org/Microsoft/node-jsonc-parser)
|
7 |
|
8 | Why?
|
9 | ----
|
10 | 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.
|
11 | - the *scanner* tokenizes the input string into tokens and token offsets
|
12 | - the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values.
|
13 | - the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values.
|
14 | - the *parse* function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion.
|
15 | - the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document.
|
16 | - the *findNodeAtLocation* API finds the node at a given location path in a JSON DOM.
|
17 | - the *format* API computes edits to format a JSON document.
|
18 | - the *modify* API computes edits to insert, remove or replace a property or value in a JSON document.
|
19 | - the *applyEdits* API applies edits to a document.
|
20 |
|
21 | Installation
|
22 | ------------
|
23 |
|
24 | npm install --save jsonc-parser
|
25 |
|
26 |
|
27 | API
|
28 | ---
|
29 |
|
30 | ### Scanner:
|
31 | ```typescript
|
32 |
|
33 | /**
|
34 | * Creates a JSON scanner on the given text.
|
35 | * If ignoreTrivia is set, whitespaces or comments are ignored.
|
36 | */
|
37 | export function createScanner(text:string, ignoreTrivia:boolean = false):JSONScanner;
|
38 |
|
39 | /**
|
40 | * The scanner object, representing a JSON scanner at a position in the input string.
|
41 | */
|
42 | export interface JSONScanner {
|
43 | /**
|
44 | * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
|
45 | */
|
46 | setPosition(pos: number): any;
|
47 | /**
|
48 | * Read the next token. Returns the token code.
|
49 | */
|
50 | scan(): SyntaxKind;
|
51 | /**
|
52 | * Returns the current scan position, which is after the last read token.
|
53 | */
|
54 | getPosition(): number;
|
55 | /**
|
56 | * Returns the last read token.
|
57 | */
|
58 | getToken(): SyntaxKind;
|
59 | /**
|
60 | * Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
|
61 | */
|
62 | getTokenValue(): string;
|
63 | /**
|
64 | * The start offset of the last read token.
|
65 | */
|
66 | getTokenOffset(): number;
|
67 | /**
|
68 | * The length of the last read token.
|
69 | */
|
70 | getTokenLength(): number;
|
71 | /**
|
72 | * The zero-based start line number of the last read token.
|
73 | */
|
74 | getTokenStartLine(): number;
|
75 | /**
|
76 | * The zero-based start character (column) of the last read token.
|
77 | */
|
78 | getTokenStartCharacter(): number;
|
79 | /**
|
80 | * An error code of the last scan.
|
81 | */
|
82 | getTokenError(): ScanError;
|
83 | }
|
84 | ```
|
85 |
|
86 | ### Parser:
|
87 | ```typescript
|
88 |
|
89 | export interface ParseOptions {
|
90 | disallowComments?: boolean;
|
91 | }
|
92 | /**
|
93 | * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
|
94 | * Therefore always check the errors list to find out if the input was valid.
|
95 | */
|
96 | export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
|
97 |
|
98 | /**
|
99 | * Parses the given text and invokes the visitor functions for each object, array and literal reached.
|
100 | */
|
101 | export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
|
102 |
|
103 | export interface JSONVisitor {
|
104 | /**
|
105 | * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
|
106 | */
|
107 | onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
|
108 | /**
|
109 | * Invoked when a property is encountered. The offset and length represent the location of the property name.
|
110 | */
|
111 | onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
|
112 | /**
|
113 | * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
|
114 | */
|
115 | onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
|
116 | /**
|
117 | * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
|
118 | */
|
119 | onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
|
120 | /**
|
121 | * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
|
122 | */
|
123 | onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
|
124 | /**
|
125 | * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
|
126 | */
|
127 | onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number) => void;
|
128 | /**
|
129 | * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
|
130 | */
|
131 | onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
|
132 | /**
|
133 | * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
|
134 | */
|
135 | onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
|
136 | /**
|
137 | * Invoked on an error.
|
138 | */
|
139 | onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;
|
140 | }
|
141 |
|
142 | /**
|
143 | * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
|
144 | */
|
145 | export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node;
|
146 |
|
147 | export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";
|
148 | export interface Node {
|
149 | type: NodeType;
|
150 | value?: any;
|
151 | offset: number;
|
152 | length: number;
|
153 | colonOffset?: number;
|
154 | parent?: Node;
|
155 | children?: Node[];
|
156 | }
|
157 |
|
158 | ```
|
159 |
|
160 | ### Utilities:
|
161 | ```typescript
|
162 | /**
|
163 | * Takes JSON with JavaScript-style comments and remove
|
164 | * them. Optionally replaces every none-newline character
|
165 | * of comments with a replaceCharacter
|
166 | */
|
167 | export declare function stripComments(text: string, replaceCh?: string): string;
|
168 |
|
169 | /**
|
170 | * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
|
171 | */
|
172 | export declare function getLocation(text: string, position: number): Location;
|
173 |
|
174 | export declare type Segment = string | number;
|
175 | export interface Location {
|
176 | /**
|
177 | * The previous property key or literal value (string, number, boolean or null) or undefined.
|
178 | */
|
179 | previousNode?: Node;
|
180 | /**
|
181 | * The path describing the location in the JSON document. The path consists of a sequence strings
|
182 | * representing an object property or numbers for array indices.
|
183 | */
|
184 | path: Segment[];
|
185 | /**
|
186 | * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
|
187 | * '*' will match a single segment, of any property name or index.
|
188 | * '**' will match a sequece of segments or no segment, of any property name or index.
|
189 | */
|
190 | matches: (patterns: Segment[]) => boolean;
|
191 | /**
|
192 | * If set, the location's offset is at a property key.
|
193 | */
|
194 | isAtPropertyKey: boolean;
|
195 | }
|
196 |
|
197 | /**
|
198 | * Finds the node at the given path in a JSON DOM.
|
199 | */
|
200 | export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
|
201 |
|
202 | /**
|
203 | * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
|
204 | */
|
205 | export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined;
|
206 |
|
207 | /**
|
208 | * Gets the JSON path of the given JSON DOM node
|
209 | */
|
210 | export function getNodePath(node: Node) : JSONPath;
|
211 |
|
212 | /**
|
213 | * Evaluates the JavaScript object of the given JSON DOM node
|
214 | */
|
215 | export function getNodeValue(node: Node): any;
|
216 |
|
217 | /**
|
218 | * Computes the edits needed to format a JSON document.
|
219 | *
|
220 | * @param documentText The input text
|
221 | * @param range The range to format or `undefined` to format the full content
|
222 | * @param options The formatting options
|
223 | * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
|
224 | * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
|
225 | * text in the original document. However, multiple edits can have
|
226 | * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
|
227 | * To apply edits to an input, you can use `applyEdits`
|
228 | */
|
229 | export function format(documentText: string, range: Range, options: FormattingOptions): Edit[];
|
230 |
|
231 |
|
232 | /**
|
233 | * Computes the edits needed to modify a value in the JSON document.
|
234 | *
|
235 | * @param documentText The input text
|
236 | * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
|
237 | * If the path points to an non-existing property or item, it will be created.
|
238 | * @param value The new value for the specified property or item. If the value is undefined,
|
239 | * the property or item will be removed.
|
240 | * @param options Options
|
241 | * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
|
242 | * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
|
243 | * text in the original document. However, multiple edits can have
|
244 | * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
|
245 | * To apply edits to an input, you can use `applyEdits`
|
246 | */
|
247 | export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): Edit[];
|
248 |
|
249 | /**
|
250 | * Applies edits to a input string.
|
251 | */
|
252 | export function applyEdits(text: string, edits: Edit[]): string;
|
253 |
|
254 | /**
|
255 | * Represents a text modification
|
256 | */
|
257 | export interface Edit {
|
258 | /**
|
259 | * The start offset of the modification.
|
260 | */
|
261 | offset: number;
|
262 | /**
|
263 | * The length of the modification. Must not be negative. Empty length represents an *insert*.
|
264 | */
|
265 | length: number;
|
266 | /**
|
267 | * The new content. Empty content represents a *remove*.
|
268 | */
|
269 | content: string;
|
270 | }
|
271 |
|
272 | /**
|
273 | * A text range in the document
|
274 | */
|
275 | export interface Range {
|
276 | /**
|
277 | * The start offset of the range.
|
278 | */
|
279 | offset: number;
|
280 | /**
|
281 | * The length of the range. Must not be negative.
|
282 | */
|
283 | length: number;
|
284 | }
|
285 |
|
286 | export interface FormattingOptions {
|
287 | /**
|
288 | * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
|
289 | */
|
290 | tabSize: number;
|
291 | /**
|
292 | * Is indentation based on spaces?
|
293 | */
|
294 | insertSpaces: boolean;
|
295 | /**
|
296 | * The default 'end of line' character
|
297 | */
|
298 | eol: string;
|
299 | }
|
300 |
|
301 | ```
|
302 |
|
303 |
|
304 | License
|
305 | -------
|
306 |
|
307 | (MIT License)
|
308 |
|
309 | Copyright 2018, Microsoft
|