jsonc-parser

  • Version 3.2.1
  • Published
  • 210 kB
  • No dependencies
  • MIT license

Install

npm i jsonc-parser
yarn add jsonc-parser
pnpm add jsonc-parser

Overview

Scanner and parser for JSON with comments.

Index

Functions

Interfaces

Enums

Type Aliases

Functions

function applyEdits

applyEdits: (text: string, edits: EditResult) => string;
  • Applies edits to an input string.

    Parameter text

    The input text

    Parameter edits

    Edit operations following the format described in .

    Returns

    The text with the applied edits.

    Throws

    An error if the edit operations are not well-formed as described in .

function createScanner

createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner;
  • Creates a JSON scanner on the given text. If ignoreTrivia is set, whitespaces or comments are ignored.

function findNodeAtLocation

findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined;
  • Finds the node at the given path in a JSON DOM.

function findNodeAtOffset

findNodeAtOffset: (
root: Node,
offset: number,
includeRightBound?: boolean
) => Node | undefined;
  • Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.

function format

format: (
documentText: string,
range: Range | undefined,
options: FormattingOptions
) => EditResult;
  • Computes the edit operations needed to format a JSON document.

    Parameter documentText

    The input text

    Parameter range

    The range to format or undefined to format the full content

    Parameter options

    The formatting options

    Returns

    The edit operations describing the formatting changes to the original document following the format described in . To apply the edit operations to the input, use .

function getLocation

getLocation: (text: string, position: number) => Location;
  • 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.

function getNodePath

getNodePath: (node: Node) => JSONPath;
  • Gets the JSON path of the given JSON DOM node

function getNodeValue

getNodeValue: (node: Node) => any;
  • Evaluates the JavaScript object of the given JSON DOM node

function modify

modify: (
text: string,
path: JSONPath,
value: any,
options: ModificationOptions
) => EditResult;
  • Computes the edit operations needed to modify a value in the JSON document.

    Parameter documentText

    The input text

    Parameter path

    The path of the value to change. The path represents either to the document root, a property or an array item. If the path points to an non-existing property or item, it will be created.

    Parameter value

    The new value for the specified property or item. If the value is undefined, the property or item will be removed.

    Parameter options

    Options

    Returns

    The edit operations describing the changes to the original document, following the format described in . To apply the edit operations to the input, use .

function parse

parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any;
  • 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. Therefore, always check the errors list to find out if the input was valid.

function parseTree

parseTree: (
text: string,
errors?: ParseError[],
options?: ParseOptions
) => Node | undefined;
  • 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.

function printParseErrorCode

printParseErrorCode: (
code: ParseErrorCode
) =>
| 'InvalidSymbol'
| 'InvalidNumberFormat'
| 'PropertyNameExpected'
| 'ValueExpected'
| 'ColonExpected'
| 'CommaExpected'
| 'CloseBraceExpected'
| 'CloseBracketExpected'
| 'EndOfFileExpected'
| 'InvalidCommentToken'
| 'UnexpectedEndOfComment'
| 'UnexpectedEndOfString'
| 'UnexpectedEndOfNumber'
| 'InvalidUnicode'
| 'InvalidEscapeCharacter'
| 'InvalidCharacter'
| '<unknown ParseErrorCode>';

    function stripComments

    stripComments: (text: string, replaceCh?: string) => string;
    • Takes JSON with JavaScript-style comments and remove them. Optionally replaces every none-newline character of comments with a replaceCharacter

    function visit

    visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any;
    • Parses the given text and invokes the visitor functions for each object, array and literal reached.

    Interfaces

    interface Edit

    interface Edit {}
    • Represents a text modification

    property content

    content: string;
    • The new content. Empty content represents a *remove*.

    property length

    length: number;
    • The length of the modification. Must not be negative. Empty length represents an *insert*.

    property offset

    offset: number;
    • The start offset of the modification.

    interface FormattingOptions

    interface FormattingOptions {}
    • Options used by when computing the formatting edit operations

    property eol

    eol?: string;
    • The default 'end of line' character. If not set, '\n' is used as default.

    property insertFinalNewline

    insertFinalNewline?: boolean;
    • If set, will add a new line at the end of the document.

    property insertSpaces

    insertSpaces?: boolean;
    • Is indentation based on spaces?

    property keepLines

    keepLines?: boolean;
    • If true, will keep line positions as is in the formatting

    property tabSize

    tabSize?: number;
    • If indentation is based on spaces (insertSpaces = true), the number of spaces that make an indent.

    interface JSONScanner

    interface JSONScanner {}
    • The scanner object, representing a JSON scanner at a position in the input string.

    method getPosition

    getPosition: () => number;
    • Returns the zero-based current scan position, which is after the last read token.

    method getToken

    getToken: () => SyntaxKind;
    • Returns the last read token.

    method getTokenError

    getTokenError: () => ScanError;
    • An error code of the last scan.

    method getTokenLength

    getTokenLength: () => number;
    • The length of the last read token.

    method getTokenOffset

    getTokenOffset: () => number;
    • The zero-based start offset of the last read token.

    method getTokenStartCharacter

    getTokenStartCharacter: () => number;
    • The zero-based start character (column) of the last read token.

    method getTokenStartLine

    getTokenStartLine: () => number;
    • The zero-based start line number of the last read token.

    method getTokenValue

    getTokenValue: () => string;
    • 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.

    method scan

    scan: () => SyntaxKind;
    • Read the next token. Returns the token code.

    method setPosition

    setPosition: (pos: number) => void;
    • Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.

    interface JSONVisitor

    interface JSONVisitor {}
    • Visitor called by when parsing JSON.

      The visitor functions have the following common parameters: - offset: Global offset within the JSON document, starting at 0 - startLine: Line number, starting at 0 - startCharacter: Start character (column) within the current line, starting at 0

      Additionally some functions have a pathSupplier parameter which can be used to obtain the current JSONPath within the document.

    property onArrayBegin

    onArrayBegin?: (
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number,
    pathSupplier: () => JSONPath
    ) => void;
    • Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.

    property onArrayEnd

    onArrayEnd?: (
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number
    ) => void;
    • Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.

    property onComment

    onComment?: (
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number
    ) => void;
    • When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.

    property onError

    onError?: (
    error: ParseErrorCode,
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number
    ) => void;
    • Invoked on an error.

    property onLiteralValue

    onLiteralValue?: (
    value: any,
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number,
    pathSupplier: () => JSONPath
    ) => void;
    • Invoked when a literal value is encountered. The offset and length represent the location of the literal value.

    property onObjectBegin

    onObjectBegin?: (
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number,
    pathSupplier: () => JSONPath
    ) => void;
    • Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.

    property onObjectEnd

    onObjectEnd?: (
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number
    ) => void;
    • Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.

    property onObjectProperty

    onObjectProperty?: (
    property: string,
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number,
    pathSupplier: () => JSONPath
    ) => void;
    • Invoked when a property is encountered. The offset and length represent the location of the property name. The JSONPath created by the pathSupplier refers to the enclosing JSON object, it does not include the property name yet.

    property onSeparator

    onSeparator?: (
    character: string,
    offset: number,
    length: number,
    startLine: number,
    startCharacter: number
    ) => void;
    • Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.

    interface Location

    interface Location {}

      property isAtPropertyKey

      isAtPropertyKey: boolean;
      • If set, the location's offset is at a property key.

      property matches

      matches: (patterns: JSONPath) => boolean;
      • Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). '*' will match a single segment of any property name or index. '**' will match a sequence of segments of any property name or index, or no segment.

      property path

      path: JSONPath;
      • The path describing the location in the JSON document. The path consists of a sequence of strings representing an object property or numbers for array indices.

      property previousNode

      previousNode?: Node;
      • The previous property key or literal value (string, number, boolean or null) or undefined.

      interface ModificationOptions

      interface ModificationOptions {}
      • Options used by when computing the modification edit operations

      property formattingOptions

      formattingOptions?: FormattingOptions;
      • Formatting options. If undefined, the newly inserted code will be inserted unformatted.

      property getInsertionIndex

      getInsertionIndex?: (properties: string[]) => number;
      • Optional function to define the insertion index given an existing list of properties.

      property isArrayInsertion

      isArrayInsertion?: boolean;
      • Default false. If JSONPath refers to an index of an array and isArrayInsertion is true, then will insert a new item at that location instead of overwriting its contents.

      interface Node

      interface Node {}

        property children

        readonly children?: Node[];

          property colonOffset

          readonly colonOffset?: number;

            property length

            readonly length: number;

              property offset

              readonly offset: number;

                property parent

                readonly parent?: Node;

                  property type

                  readonly type: NodeType;

                    property value

                    readonly value?: any;

                      interface ParseError

                      interface ParseError {}

                        property error

                        error: ParseErrorCode;

                          property length

                          length: number;

                            property offset

                            offset: number;

                              interface ParseOptions

                              interface ParseOptions {}

                                property allowEmptyContent

                                allowEmptyContent?: boolean;

                                  property allowTrailingComma

                                  allowTrailingComma?: boolean;

                                    property disallowComments

                                    disallowComments?: boolean;

                                      interface Range

                                      interface Range {}
                                      • A text range in the document

                                      property length

                                      length: number;
                                      • The length of the range. Must not be negative.

                                      property offset

                                      offset: number;
                                      • The start offset of the range.

                                      Enums

                                      enum ParseErrorCode

                                      const enum ParseErrorCode {
                                      InvalidSymbol = 1,
                                      InvalidNumberFormat = 2,
                                      PropertyNameExpected = 3,
                                      ValueExpected = 4,
                                      ColonExpected = 5,
                                      CommaExpected = 6,
                                      CloseBraceExpected = 7,
                                      CloseBracketExpected = 8,
                                      EndOfFileExpected = 9,
                                      InvalidCommentToken = 10,
                                      UnexpectedEndOfComment = 11,
                                      UnexpectedEndOfString = 12,
                                      UnexpectedEndOfNumber = 13,
                                      InvalidUnicode = 14,
                                      InvalidEscapeCharacter = 15,
                                      InvalidCharacter = 16,
                                      }

                                        member CloseBraceExpected

                                        CloseBraceExpected = 7

                                          member CloseBracketExpected

                                          CloseBracketExpected = 8

                                            member ColonExpected

                                            ColonExpected = 5

                                              member CommaExpected

                                              CommaExpected = 6

                                                member EndOfFileExpected

                                                EndOfFileExpected = 9

                                                  member InvalidCharacter

                                                  InvalidCharacter = 16

                                                    member InvalidCommentToken

                                                    InvalidCommentToken = 10

                                                      member InvalidEscapeCharacter

                                                      InvalidEscapeCharacter = 15

                                                        member InvalidNumberFormat

                                                        InvalidNumberFormat = 2

                                                          member InvalidSymbol

                                                          InvalidSymbol = 1

                                                            member InvalidUnicode

                                                            InvalidUnicode = 14

                                                              member PropertyNameExpected

                                                              PropertyNameExpected = 3

                                                                member UnexpectedEndOfComment

                                                                UnexpectedEndOfComment = 11

                                                                  member UnexpectedEndOfNumber

                                                                  UnexpectedEndOfNumber = 13

                                                                    member UnexpectedEndOfString

                                                                    UnexpectedEndOfString = 12

                                                                      member ValueExpected

                                                                      ValueExpected = 4

                                                                        enum ScanError

                                                                        const enum ScanError {
                                                                        None = 0,
                                                                        UnexpectedEndOfComment = 1,
                                                                        UnexpectedEndOfString = 2,
                                                                        UnexpectedEndOfNumber = 3,
                                                                        InvalidUnicode = 4,
                                                                        InvalidEscapeCharacter = 5,
                                                                        InvalidCharacter = 6,
                                                                        }

                                                                          member InvalidCharacter

                                                                          InvalidCharacter = 6

                                                                            member InvalidEscapeCharacter

                                                                            InvalidEscapeCharacter = 5

                                                                              member InvalidUnicode

                                                                              InvalidUnicode = 4

                                                                                member None

                                                                                None = 0

                                                                                  member UnexpectedEndOfComment

                                                                                  UnexpectedEndOfComment = 1

                                                                                    member UnexpectedEndOfNumber

                                                                                    UnexpectedEndOfNumber = 3

                                                                                      member UnexpectedEndOfString

                                                                                      UnexpectedEndOfString = 2

                                                                                        enum SyntaxKind

                                                                                        const enum SyntaxKind {
                                                                                        OpenBraceToken = 1,
                                                                                        CloseBraceToken = 2,
                                                                                        OpenBracketToken = 3,
                                                                                        CloseBracketToken = 4,
                                                                                        CommaToken = 5,
                                                                                        ColonToken = 6,
                                                                                        NullKeyword = 7,
                                                                                        TrueKeyword = 8,
                                                                                        FalseKeyword = 9,
                                                                                        StringLiteral = 10,
                                                                                        NumericLiteral = 11,
                                                                                        LineCommentTrivia = 12,
                                                                                        BlockCommentTrivia = 13,
                                                                                        LineBreakTrivia = 14,
                                                                                        Trivia = 15,
                                                                                        Unknown = 16,
                                                                                        EOF = 17,
                                                                                        }

                                                                                          member BlockCommentTrivia

                                                                                          BlockCommentTrivia = 13

                                                                                            member CloseBraceToken

                                                                                            CloseBraceToken = 2

                                                                                              member CloseBracketToken

                                                                                              CloseBracketToken = 4

                                                                                                member ColonToken

                                                                                                ColonToken = 6

                                                                                                  member CommaToken

                                                                                                  CommaToken = 5

                                                                                                    member EOF

                                                                                                    EOF = 17

                                                                                                      member FalseKeyword

                                                                                                      FalseKeyword = 9

                                                                                                        member LineBreakTrivia

                                                                                                        LineBreakTrivia = 14

                                                                                                          member LineCommentTrivia

                                                                                                          LineCommentTrivia = 12

                                                                                                            member NullKeyword

                                                                                                            NullKeyword = 7

                                                                                                              member NumericLiteral

                                                                                                              NumericLiteral = 11

                                                                                                                member OpenBraceToken

                                                                                                                OpenBraceToken = 1

                                                                                                                  member OpenBracketToken

                                                                                                                  OpenBracketToken = 3

                                                                                                                    member StringLiteral

                                                                                                                    StringLiteral = 10

                                                                                                                      member Trivia

                                                                                                                      Trivia = 15

                                                                                                                        member TrueKeyword

                                                                                                                        TrueKeyword = 8

                                                                                                                          member Unknown

                                                                                                                          Unknown = 16

                                                                                                                            Type Aliases

                                                                                                                            type EditResult

                                                                                                                            type EditResult = Edit[];
                                                                                                                            • An edit result describes a textual edit operation. It is the result of a and operation. It consist of one or more edits describing insertions, replacements or removals of text segments. * The offsets of the edits refer to the original state of the document. * No two edits change or remove the same range of text in the original document. * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. * The order in the array defines which edit is applied first. To apply an edit result use . In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data.

                                                                                                                            type JSONPath

                                                                                                                            type JSONPath = Segment[];

                                                                                                                              type NodeType

                                                                                                                              type NodeType =
                                                                                                                              | 'object'
                                                                                                                              | 'array'
                                                                                                                              | 'property'
                                                                                                                              | 'string'
                                                                                                                              | 'number'
                                                                                                                              | 'boolean'
                                                                                                                              | 'null';

                                                                                                                                type Segment

                                                                                                                                type Segment = string | number;
                                                                                                                                • A segment. Either a string representing an object property name or a number (starting at 0) for array indices.

                                                                                                                                Package Files (1)

                                                                                                                                Dependencies (0)

                                                                                                                                No dependencies.

                                                                                                                                Dev Dependencies (8)

                                                                                                                                Peer Dependencies (0)

                                                                                                                                No peer dependencies.

                                                                                                                                Badge

                                                                                                                                To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/jsonc-parser.

                                                                                                                                • Markdown
                                                                                                                                  [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/jsonc-parser)
                                                                                                                                • HTML
                                                                                                                                  <a href="https://www.jsdocs.io/package/jsonc-parser"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>