UNPKG

14.3 kBMarkdownView Raw
1# jsonc-parser
2Scanner 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://github.com/microsoft/node-jsonc-parser/workflows/Tests/badge.svg)](https://github.com/microsoft/node-jsonc-parser/workflows/Tests)
7[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
9Why?
10----
11JSONC 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.
12 - the *scanner* tokenizes the input string into tokens and token offsets
13 - the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values.
14 - the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values.
15 - the *parse* function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion.
16 - the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document.
17 - the *findNodeAtLocation* API finds the node at a given location path in a JSON DOM.
18 - the *format* API computes edits to format a JSON document.
19 - the *modify* API computes edits to insert, remove or replace a property or value in a JSON document.
20 - the *applyEdits* API applies edits to a document.
21
22Installation
23------------
24
25```
26npm install --save jsonc-parser
27```
28
29API
30---
31
32### Scanner:
33```typescript
34
35/**
36 * Creates a JSON scanner on the given text.
37 * If ignoreTrivia is set, whitespaces or comments are ignored.
38 */
39export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner;
40
41/**
42 * The scanner object, representing a JSON scanner at a position in the input string.
43 */
44export interface JSONScanner {
45 /**
46 * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
47 */
48 setPosition(pos: number): any;
49 /**
50 * Read the next token. Returns the token code.
51 */
52 scan(): SyntaxKind;
53 /**
54 * Returns the zero-based current scan position, which is after the last read token.
55 */
56 getPosition(): number;
57 /**
58 * Returns the last read token.
59 */
60 getToken(): SyntaxKind;
61 /**
62 * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false.
63 */
64 getTokenValue(): string;
65 /**
66 * The zero-based start offset of the last read token.
67 */
68 getTokenOffset(): number;
69 /**
70 * The length of the last read token.
71 */
72 getTokenLength(): number;
73 /**
74 * The zero-based start line number of the last read token.
75 */
76 getTokenStartLine(): number;
77 /**
78 * The zero-based start character (column) of the last read token.
79 */
80 getTokenStartCharacter(): number;
81 /**
82 * An error code of the last scan.
83 */
84 getTokenError(): ScanError;
85}
86```
87
88### Parser:
89```typescript
90
91export interface ParseOptions {
92 disallowComments?: boolean;
93 allowTrailingComma?: boolean;
94 allowEmptyContent?: boolean;
95}
96/**
97 * 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.
98 * Therefore always check the errors list to find out if the input was valid.
99 */
100export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
101
102/**
103 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
104 */
105export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
106
107/**
108 * Visitor called by {@linkcode visit} when parsing JSON.
109 *
110 * The visitor functions have the following common parameters:
111 * - `offset`: Global offset within the JSON document, starting at 0
112 * - `startLine`: Line number, starting at 0
113 * - `startCharacter`: Start character (column) within the current line, starting at 0
114 *
115 * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the
116 * current `JSONPath` within the document.
117 */
118export interface JSONVisitor {
119 /**
120 * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
121 * When `false` is returned, the array items will not be visited.
122 */
123 onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void | boolean;
124
125 /**
126 * Invoked when a property is encountered. The offset and length represent the location of the property name.
127 * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the
128 * property name yet.
129 */
130 onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
131 /**
132 * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
133 */
134 onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
135 /**
136 * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
137 * When `false` is returned, the array items will not be visited.*
138 */
139 onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void | boolean;
140 /**
141 * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
142 */
143 onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
144 /**
145 * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
146 */
147 onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
148 /**
149 * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
150 */
151 onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void;
152 /**
153 * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
154 */
155 onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void;
156 /**
157 * Invoked on an error.
158 */
159 onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;
160}
161
162/**
163 * 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.
164 */
165export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined;
166
167export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";
168export interface Node {
169 type: NodeType;
170 value?: any;
171 offset: number;
172 length: number;
173 colonOffset?: number;
174 parent?: Node;
175 children?: Node[];
176}
177
178```
179
180### Utilities:
181```typescript
182/**
183 * Takes JSON with JavaScript-style comments and remove
184 * them. Optionally replaces every none-newline character
185 * of comments with a replaceCharacter
186 */
187export declare function stripComments(text: string, replaceCh?: string): string;
188
189/**
190 * 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.
191 */
192export declare function getLocation(text: string, position: number): Location;
193
194/**
195 * A {@linkcode JSONPath} segment. Either a string representing an object property name
196 * or a number (starting at 0) for array indices.
197 */
198export declare type Segment = string | number;
199export declare type JSONPath = Segment[];
200export interface Location {
201 /**
202 * The previous property key or literal value (string, number, boolean or null) or undefined.
203 */
204 previousNode?: Node;
205 /**
206 * The path describing the location in the JSON document. The path consists of a sequence strings
207 * representing an object property or numbers for array indices.
208 */
209 path: JSONPath;
210 /**
211 * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
212 * '*' will match a single segment, of any property name or index.
213 * '**' will match a sequence of segments or no segment, of any property name or index.
214 */
215 matches: (patterns: JSONPath) => boolean;
216 /**
217 * If set, the location's offset is at a property key.
218 */
219 isAtPropertyKey: boolean;
220}
221
222/**
223 * Finds the node at the given path in a JSON DOM.
224 */
225export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
226
227/**
228 * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
229 */
230export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined;
231
232/**
233 * Gets the JSON path of the given JSON DOM node
234 */
235export function getNodePath(node: Node): JSONPath;
236
237/**
238 * Evaluates the JavaScript object of the given JSON DOM node
239 */
240export function getNodeValue(node: Node): any;
241
242/**
243 * Computes the edit operations needed to format a JSON document.
244 *
245 * @param documentText The input text
246 * @param range The range to format or `undefined` to format the full content
247 * @param options The formatting options
248 * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.
249 * To apply the edit operations to the input, use {@linkcode applyEdits}.
250 */
251export function format(documentText: string, range: Range, options: FormattingOptions): EditResult;
252
253/**
254 * Computes the edit operations needed to modify a value in the JSON document.
255 *
256 * @param documentText The input text
257 * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
258 * If the path points to an non-existing property or item, it will be created.
259 * @param value The new value for the specified property or item. If the value is undefined,
260 * the property or item will be removed.
261 * @param options Options
262 * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.
263 * To apply the edit operations to the input, use {@linkcode applyEdits}.
264 */
265export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
266
267/**
268 * Applies edits to an input string.
269 * @param text The input text
270 * @param edits Edit operations following the format described in {@linkcode EditResult}.
271 * @returns The text with the applied edits.
272 * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.
273 */
274export function applyEdits(text: string, edits: EditResult): string;
275
276/**
277 * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation.
278 * It consist of one or more edits describing insertions, replacements or removals of text segments.
279 * * The offsets of the edits refer to the original state of the document.
280 * * No two edits change or remove the same range of text in the original document.
281 * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace.
282 * * The order in the array defines which edit is applied first.
283 * To apply an edit result use {@linkcode applyEdits}.
284 * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data.
285 */
286export type EditResult = Edit[];
287
288/**
289 * Represents a text modification
290 */
291export interface Edit {
292 /**
293 * The start offset of the modification.
294 */
295 offset: number;
296 /**
297 * The length of the modification. Must not be negative. Empty length represents an *insert*.
298 */
299 length: number;
300 /**
301 * The new content. Empty content represents a *remove*.
302 */
303 content: string;
304}
305
306/**
307 * A text range in the document
308*/
309export interface Range {
310 /**
311 * The start offset of the range.
312 */
313 offset: number;
314 /**
315 * The length of the range. Must not be negative.
316 */
317 length: number;
318}
319
320/**
321 * Options used by {@linkcode format} when computing the formatting edit operations
322 */
323export interface FormattingOptions {
324 /**
325 * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
326 */
327 tabSize: number;
328 /**
329 * Is indentation based on spaces?
330 */
331 insertSpaces: boolean;
332 /**
333 * The default 'end of line' character
334 */
335 eol: string;
336}
337
338/**
339 * Options used by {@linkcode modify} when computing the modification edit operations
340 */
341export interface ModificationOptions {
342 /**
343 * Formatting options. If undefined, the newly inserted code will be inserted unformatted.
344 */
345 formattingOptions?: FormattingOptions;
346 /**
347 * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then
348 * {@linkcode modify} will insert a new item at that location instead of overwriting its contents.
349 */
350 isArrayInsertion?: boolean;
351 /**
352 * Optional function to define the insertion index given an existing list of properties.
353 */
354 getInsertionIndex?: (properties: string[]) => number;
355}
356```
357
358
359License
360-------
361
362(MIT License)
363
364Copyright 2018, Microsoft