版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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