{"id":13484990,"url":"https://github.com/microsoft/node-jsonc-parser","last_synced_at":"2025-05-13T17:09:48.192Z","repository":{"id":8307543,"uuid":"56496360","full_name":"microsoft/node-jsonc-parser","owner":"microsoft","description":"Scanner and parser for JSON with comments.","archived":false,"fork":false,"pushed_at":"2025-04-14T07:22:40.000Z","size":2015,"stargazers_count":657,"open_issues_count":20,"forks_count":53,"subscribers_count":28,"default_branch":"main","last_synced_at":"2025-05-09T04:08:24.043Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/microsoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-04-18T09:51:11.000Z","updated_at":"2025-05-06T16:04:30.000Z","dependencies_parsed_at":"2024-06-01T10:49:38.299Z","dependency_job_id":"903ea088-4fc6-4674-b12d-f97cf2ef47f9","html_url":"https://github.com/microsoft/node-jsonc-parser","commit_stats":{"total_commits":137,"total_committers":21,"mean_commits":6.523809523809524,"dds":"0.26277372262773724","last_synced_commit":"3c9b4203d663061d87d4d34dd0004690aef94db5"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fnode-jsonc-parser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fnode-jsonc-parser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fnode-jsonc-parser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/microsoft%2Fnode-jsonc-parser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/microsoft","download_url":"https://codeload.github.com/microsoft/node-jsonc-parser/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253398098,"owners_count":21902036,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T17:01:41.767Z","updated_at":"2025-05-13T17:09:48.136Z","avatar_url":"https://github.com/microsoft.png","language":"TypeScript","readme":"# jsonc-parser\nScanner and parser for JSON with comments.\n\n[![npm Package](https://img.shields.io/npm/v/jsonc-parser.svg?style=flat-square)](https://www.npmjs.org/package/jsonc-parser)\n[![NPM Downloads](https://img.shields.io/npm/dm/jsonc-parser.svg)](https://npmjs.org/package/jsonc-parser)\n[![Build Status](https://github.com/microsoft/node-jsonc-parser/workflows/Tests/badge.svg)](https://github.com/microsoft/node-jsonc-parser/workflows/Tests)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nWhy?\n----\nJSONC 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.\n - the *scanner* tokenizes the input string into tokens and token offsets\n - the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values.\n - the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values.\n - the *parse* function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion.\n - the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document.\n - the *findNodeAtLocation* API finds the node at a given location path in a JSON DOM.\n - the *format* API computes edits to format a JSON document.\n - the *modify* API computes edits to insert, remove or replace a property or value in a JSON document.\n - the *applyEdits* API applies edits to a document.\n\nInstallation\n------------\n\n```\nnpm install --save jsonc-parser\n```\n\nAPI\n---\n\n### Scanner:\n```typescript\n\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner;\n\n/**\n * The scanner object, representing a JSON scanner at a position in the input string.\n */\nexport interface JSONScanner {\n    /**\n     * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.\n     */\n    setPosition(pos: number): any;\n    /**\n     * Read the next token. Returns the token code.\n     */\n    scan(): SyntaxKind;\n    /**\n     * Returns the zero-based current scan position, which is after the last read token.\n     */\n    getPosition(): number;\n    /**\n     * Returns the last read token.\n     */\n    getToken(): SyntaxKind;\n    /**\n     * 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.\n     */\n    getTokenValue(): string;\n    /**\n     * The zero-based start offset of the last read token.\n     */\n    getTokenOffset(): number;\n    /**\n     * The length of the last read token.\n     */\n    getTokenLength(): number;\n    /**\n     * The zero-based start line number of the last read token.\n     */\n    getTokenStartLine(): number;\n    /**\n     * The zero-based start character (column) of the last read token.\n     */\n    getTokenStartCharacter(): number;\n    /**\n     * An error code of the last scan.\n     */\n    getTokenError(): ScanError;\n}\n```\n\n### Parser:\n```typescript\n\nexport interface ParseOptions {\n    disallowComments?: boolean;\n    allowTrailingComma?: boolean;\n    allowEmptyContent?: boolean;\n}\n/**\n * 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.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;\n\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;\n\n/**\n * Visitor called by {@linkcode visit} when parsing JSON.\n *\n * The visitor functions have the following common parameters:\n * - `offset`: Global offset within the JSON document, starting at 0\n * - `startLine`: Line number, starting at 0\n * - `startCharacter`: Start character (column) within the current line, starting at 0\n *\n * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the\n * current `JSONPath` within the document.\n */\nexport interface JSONVisitor {\n    /**\n     * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.\n     * When `false` is returned, the array items will not be visited.\n     */\n    onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () =\u003e JSONPath) =\u003e void | boolean;\n\n    /**\n     * Invoked when a property is encountered. The offset and length represent the location of the property name.\n     * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the\n     * property name yet.\n     */\n    onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () =\u003e JSONPath) =\u003e void;\n    /**\n     * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.\n     */\n    onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) =\u003e void;\n    /**\n     * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.\n     * When `false` is returned, the array items will not be visited.*\n     */\n    onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () =\u003e JSONPath) =\u003e void | boolean;\n    /**\n     * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.\n     */\n    onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) =\u003e void;\n    /**\n     * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.\n     */\n    onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () =\u003e JSONPath) =\u003e void;\n    /**\n     * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.\n     */\n    onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) =\u003e void;\n    /**\n     * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.\n     */\n    onComment?: (offset: number, length: number, startLine: number, startCharacter: number) =\u003e void;\n    /**\n     * Invoked on an error.\n     */\n    onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) =\u003e void;\n}\n\n/**\n * 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.\n */\nexport declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined;\n\nexport declare type NodeType = \"object\" | \"array\" | \"property\" | \"string\" | \"number\" | \"boolean\" | \"null\";\nexport interface Node {\n    type: NodeType;\n    value?: any;\n    offset: number;\n    length: number;\n    colonOffset?: number;\n    parent?: Node;\n    children?: Node[];\n}\n\n```\n\n### Utilities:\n```typescript\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport declare function stripComments(text: string, replaceCh?: string): string;\n\n/**\n * 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.\n */\nexport declare function getLocation(text: string, position: number): Location;\n\n/**\n * A {@linkcode JSONPath} segment. Either a string representing an object property name\n * or a number (starting at 0) for array indices.\n */\nexport declare type Segment = string | number;\nexport declare type JSONPath = Segment[];\nexport interface Location {\n    /**\n     * The previous property key or literal value (string, number, boolean or null) or undefined.\n     */\n    previousNode?: Node;\n    /**\n     * The path describing the location in the JSON document. The path consists of a sequence strings\n     * representing an object property or numbers for array indices.\n     */\n    path: JSONPath;\n    /**\n     * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).\n     * '*' will match a single segment, of any property name or index.\n     * '**' will match a sequence of segments or no segment, of any property name or index.\n     */\n    matches: (patterns: JSONPath) =\u003e boolean;\n    /**\n     * If set, the location's offset is at a property key.\n     */\n    isAtPropertyKey: boolean;\n}\n\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;\n\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined;\n\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node: Node): JSONPath;\n\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node: Node): any;\n\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText: string, range: Range, options: FormattingOptions): EditResult;\n\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;\n\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text: string, edits: EditResult): string;\n\n/**\n * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation.\n * It consist of one or more edits describing insertions, replacements or removals of text segments.\n * * The offsets of the edits refer to the original state of the document.\n * * No two edits change or remove the same range of text in the original document.\n * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace.\n * * The order in the array defines which edit is applied first.\n * To apply an edit result use {@linkcode applyEdits}.\n * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data.\n */\nexport type EditResult = Edit[];\n\n/**\n * Represents a text modification\n */\nexport interface Edit {\n    /**\n     * The start offset of the modification.\n     */\n    offset: number;\n    /**\n     * The length of the modification. Must not be negative. Empty length represents an *insert*.\n     */\n    length: number;\n    /**\n     * The new content. Empty content represents a *remove*.\n     */\n    content: string;\n}\n\n/**\n * A text range in the document\n*/\nexport interface Range {\n    /**\n     * The start offset of the range.\n     */\n    offset: number;\n    /**\n     * The length of the range. Must not be negative.\n     */\n    length: number;\n}\n\n/**\n * Options used by {@linkcode format} when computing the formatting edit operations\n */\nexport interface FormattingOptions {\n    /**\n     * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?\n     */\n    tabSize: number;\n    /**\n     * Is indentation based on spaces?\n     */\n    insertSpaces: boolean;\n    /**\n     * The default 'end of line' character\n     */\n    eol: string;\n}\n\n/**\n * Options used by {@linkcode modify} when computing the modification edit operations\n */\nexport interface ModificationOptions {\n    /**\n     * Formatting options. If undefined, the newly inserted code will be inserted unformatted.\n    */\n    formattingOptions?: FormattingOptions;\n    /**\n     * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then\n     * {@linkcode modify} will insert a new item at that location instead of overwriting its contents.\n     */\n    isArrayInsertion?: boolean;\n    /**\n     * Optional function to define the insertion index given an existing list of properties.\n     */\n    getInsertionIndex?: (properties: string[]) =\u003e number;\n}\n```\n\n\nLicense\n-------\n\n(MIT License)\n\nCopyright 2018, Microsoft\n","funding_links":[],"categories":["TypeScript","Repository"],"sub_categories":["Object / JSON / JSON Schema"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2Fnode-jsonc-parser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmicrosoft%2Fnode-jsonc-parser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmicrosoft%2Fnode-jsonc-parser/lists"}