| 1 |
# jsonc-parser |
| 2 |
Scanner and parser for JSON with comments. |
| 3 |
|
| 4 |
[](https://www.npmjs.org/package/jsonc-parser](https://www.npmjs.org/package/jsonc-parser](https://www.npmjs.org/package/jsonc-parser) |
| 5 |
[](https://npmjs.org/package/jsonc-parser](https://npmjs.org/package/jsonc-parser](https://npmjs.org/package/jsonc-parser) |
| 6 |
[](https://github.com/microsoft/node-jsonc-parser/workflows/Tests](https://github.com/microsoft/node-jsonc-parser/workflows/Tests](https://github.com/microsoft/node-jsonc-parser/workflows/Tests) |
| 7 |
[](https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT) |
| 8 |
|
| 9 |
Why? |
| 10 |
---- |
| 11 |
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. |
| 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 |
|
| 22 |
Installation |
| 23 |
------------ |
| 24 |
|
| 25 |
``` |
| 26 |
npm install --save jsonc-parser |
| 27 |
``` |
| 28 |
|
| 29 |
API |
| 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 |
*/ |
| 39 |
export 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 |
*/ |
| 44 |
export 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 |
|
| 91 |
export 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 |
*/ |
| 100 |
export 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 |
*/ |
| 105 |
export 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 |
*/ |
| 118 |
export 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 |
*/ |
| 165 |
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined; |
| 166 |
|
| 167 |
export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null"; |
| 168 |
export 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 |
*/ |
| 187 |
export 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 |
*/ |
| 192 |
export 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 |
*/ |
| 198 |
export declare type Segment = string | number; |
| 199 |
export declare type JSONPath = Segment[]; |
| 200 |
export 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 |
*/ |
| 225 |
export 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 |
*/ |
| 230 |
export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined; |
| 231 |
|
| 232 |
/** |
| 233 |
* Gets the JSON path of the given JSON DOM node |
| 234 |
*/ |
| 235 |
export function getNodePath(node: Node): JSONPath; |
| 236 |
|
| 237 |
/** |
| 238 |
* Evaluates the JavaScript object of the given JSON DOM node |
| 239 |
*/ |
| 240 |
export 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 |
*/ |
| 251 |
export 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 |
*/ |
| 265 |
export 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 |
*/ |
| 274 |
export 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 |
*/ |
| 286 |
export type EditResult = Edit[]; |
| 287 |
|
| 288 |
/** |
| 289 |
* Represents a text modification |
| 290 |
*/ |
| 291 |
export 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 |
*/ |
| 309 |
export 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 |
*/ |
| 323 |
export 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 |
*/ |
| 341 |
export 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 |
|
| 359 |
License |
| 360 |
------- |
| 361 |
|
| 362 |
(MIT License) |
| 363 |
|
| 364 |
Copyright 2018, Microsoft |
| 365 |
|