### Install comment-json Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Install the comment-json package using npm. ```sh $ npm i comment-json ``` -------------------------------- ### stringify() example Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Example demonstrating the usage of `stringify` with pretty-printing, preserving comments. ```javascript console.log(stringify(parsed, null, 2)) // Exactly the same as `content` ``` ```javascript console.log(stringify(result)) // {"a":1} console.log(stringify(result, null, 2)) // is the same as `code` ``` -------------------------------- ### Example Usage Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/types.md Example of how to use the comment position constants. ```typescript import { PREFIX_BEFORE, PREFIX_AFTER_ALL } from 'comment-json' moveComments(obj, obj, { where: PREFIX_BEFORE, key: 'foo' }, { where: PREFIX_AFTER_ALL } ) ``` -------------------------------- ### Install Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Install the comment-json package using npm. ```bash npm install comment-json ``` -------------------------------- ### unshift example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using unshift on a CommentArray to add elements to the beginning and observe comment repositioning. ```javascript const arr = parse('[2, 3]') // with comments arr.unshift(1) // [1, 2, 3] // Comments that were at indices 0, 1 are now at indices 1, 2 ``` -------------------------------- ### Transforming during parse Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md An example demonstrating how to apply default values during parsing if certain keys are missing in the JSON string. ```javascript const { parse } = require('comment-json') function parseWithDefaults(jsonString) { const defaults = { timeout: 5000, retries: 3, verbose: false } const parsed = parse(jsonString, (key, value) => { // Apply defaults for missing top-level keys return value }) return { ...defaults, ...parsed } } ``` -------------------------------- ### Example Usage of parse() Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md An example demonstrating how to use the parse() function with a JSON string containing comments and how to inspect the parsed result. ```javascript const {inspect} = require('util') const parsed = parse(content) console.log( inspect(parsed, { // Since 4.0.0, symbol properties of comments are not enumerable, // use `showHidden: true` to print them showHidden: true }) ) console.log(Object.keys(parsed)) // > ['foo', 'bar'] console.log(stringify(parsed, null, 2)) // 🚀 Exact as the content above! 🚀 ``` -------------------------------- ### Basic assignment of all properties Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/assign.md This example demonstrates the basic usage of the `assign` function to copy all enumerable properties and their associated comments from a source object to a target object. ```javascript const { parse, assign, stringify } = require('comment-json') const source = parse(`{ // User info "name": "Alice", // Full name "email": "alice@example.com" }`) const target = { id: 1 } assign(target, source) console.log(target) // { id: 1, name: 'Alice', email: 'alice@example.com' } // with all comment Symbol properties from source console.log(stringify(target, null, 2)) // { // "id": 1, // // User info // "name": "Alice", // Full name // "email": "alice@example.com" // } ``` -------------------------------- ### concat example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using concat on CommentArrays to combine arrays while preserving comments. ```javascript const arr1 = parse('[1, 2]') // with comments const arr2 = parse('[3, 4]') // with comments const result = arr1.concat(arr2) // [1, 2, 3, 4] // Comments from arr1 at indices 0, 1 // Comments from arr2 at indices 2, 3 ``` -------------------------------- ### Default: preserve everything Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example demonstrating the default behavior of the parse() function, which preserves all comments and blank lines. ```javascript const { parse } = require('comment-json') const obj = parse(`{ // comment before "key": "value" // comment after }`) // Result contains Symbol properties for all comments and blank lines console.log(Object.getOwnPropertySymbols(obj).length > 0) // true ``` -------------------------------- ### reverse example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using reverse on a CommentArray to reverse the array in place and observe comment repositioning. ```javascript const arr = parse('[1, 2, 3]') // with comments arr.reverse() // [3, 2, 1] // Comments follow the elements to their new positions ``` -------------------------------- ### sort example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using sort on a CommentArray to sort the array in place and observe comment repositioning. ```javascript const arr = parse('["b", "a", "c"]') // with comments arr.sort() // ["a", "b", "c"] // Comments follow elements to their sorted positions ``` -------------------------------- ### Assignment with specific keys Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/assign.md This example shows how to use the `assign` function to copy only specific properties and their associated comments from a source object to a target object by providing an array of keys. ```javascript const { parse, assign, stringify } = require('comment-json') const source = parse(`{ // First name "firstName": "Bob", // User first name // Last name "lastName": "Smith", // User last name // Age "age": 30 }`) const target = {} assign(target, source, ['firstName', 'lastName']) console.log(stringify(target, null, 2)) // { // // First name // "firstName": "Bob", // User first name // // Last name // "lastName": "Smith" // User last name // } // Note: 'age' is not included, and 'before-all' comment is also excluded ``` -------------------------------- ### TypeScript usage Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Example of using comment-json with TypeScript, including imports for various types and functions. ```typescript import { parse, stringify, CommentArray, CommentJSONValue, ParseOptions } from 'comment-json' const obj: CommentJSONValue = parse(json) const output: string = stringify(obj, null, 2) ``` -------------------------------- ### SyntaxError Example 1 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a SyntaxError when parsing invalid JSON with an unexpected token. ```javascript const { parse } = require('comment-json') try { parse('{\"invalid\": }') } catch (error) { console.log(error.name) // 'SyntaxError' console.log(error.message) // Unexpected token '}', "..." is not valid JSON console.log(error.line) // Line number console.log(error.column) // Column number } ``` -------------------------------- ### TypeError Example 1 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a TypeError when the target argument for assign() is null or undefined. ```javascript const { assign } = require('comment-json') try { assign(null, {}) } catch (error) { console.log(error.name) // 'TypeError' console.log(error.message) // 'Cannot convert undefined or null to object' } ``` -------------------------------- ### SyntaxError Example 2 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a SyntaxError when parsing JSON input that ends prematurely. ```javascript try { parse('{') } catch (error) { console.log(error.message) // 'Unexpected end of JSON input' console.log(error.line) console.log(error.column) } ``` -------------------------------- ### assign() example: Copying properties with comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Demonstrates copying properties and their comments from a parsed object to a target object using `assign`. ```javascript const parsed = parse(`// before all { // This is a comment "foo": "bar" }`) const obj = assign({ bar: 'baz' }, parsed) stringify(obj, null, 2) // // before all // { // "bar": "baz", // // This is a comment // "foo": "bar" // } ``` -------------------------------- ### Stringify with comments (formatted) Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example of stringifying a parsed object back into JSON format, preserving comments and applying formatting. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // configuration "key": "value" // inline comment }`) const output = stringify(obj, null, 2) console.log(output) // { // // configuration // "key": "value" // inline comment // } ``` -------------------------------- ### TypeError Example 2 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a TypeError when the keys argument for assign() is not an array or undefined. ```javascript try { assign({}, {}, 'not-an-array') } catch (error) { console.log(error.message) // 'keys must be array or undefined' } ``` -------------------------------- ### shift example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using shift on a CommentArray to remove the first element and observe comment repositioning. ```javascript const arr = parse('[1, 2, 3]') // with comments arr.shift() // [2, 3] // Comments that were at indices 1, 2 are now at indices 0, 1 ``` -------------------------------- ### splice example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using splice on a CommentArray to replace an element and observe comment repositioning. ```javascript const arr = parse('[1, 2, 3] // item 1, 2, 3') arr.splice(1, 1, 10) // Replace element at index 1 // Comments are repositioned: what was at index 2 is now at index 1 ``` -------------------------------- ### slice example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using slice on a CommentArray to create a shallow copy of a portion of the array, preserving comments. ```javascript const arr = parse('[1, 2, 3]') // with comments const sub = arr.slice(1, 3) // [2, 3] with comments for indices 1 and 2 ``` -------------------------------- ### Remove both comments and blank lines Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example of parsing JSON to remove both comments and blank lines, mimicking standard JSON.parse behavior. ```javascript const { parse } = require('comment-json') const obj = parse(`{ // comment "key": "value" }`, null, { no_comments: true, no_blank_lines: true }) // Equivalent to JSON.parse() behavior console.log(Object.getOwnPropertySymbols(obj)) // [] ``` -------------------------------- ### Sorting keys while preserving comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/assign.md This example shows how to use `assign` to copy properties in a specific order (sorted keys) while ensuring that all associated comments are preserved. ```javascript const { parse, assign, stringify } = require('comment-json') const parsed = parse(`{ // Beta feature "b": 2, // Alpha feature "a": 1, // Gamma feature "c": 3 }`) // Assign in sorted key order const sorted = assign({}, parsed, Object.keys(parsed).sort()) console.log(stringify(sorted, null, 2)) // { // // Alpha feature // "a": 1, // // Beta feature // "b": 2, // // Gamma feature // "c": 3 // } ``` -------------------------------- ### pop example Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Example of using pop on a CommentArray to remove the last element. ```javascript const arr = parse('[1, 2, 3]') // with comments arr.pop() // [1, 2] // Comments for index 2 are removed ``` -------------------------------- ### Reviver Example: Converting numeric strings to BigInt Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/types.md An example of a Reviver function that converts numeric strings to BigInts if the source is purely numeric. ```typescript const reviver: Reviver = (key, value, context) => { if (context && /^[0-9]+$/.test(context.source)) { return BigInt(context.source) } return value } ``` -------------------------------- ### Stringify with replacer function Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example of using a replacer function with stringify to filter out specific fields from the output. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // user details "name": "Alice", // internal field "id": 12345 }`) // Filter out sensitive fields const filtered = stringify(obj, (key, value) => { if (key === 'id') return undefined return value }, 2) console.log(filtered) // { // // user details // "name": "Alice" // } ``` -------------------------------- ### Remove comments but keep formatting structure Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example showing how to parse JSON while removing comments but retaining the overall formatting structure. ```javascript const { parse } = require('comment-json') const obj = parse(`{ // configuration "timeout": 5000, // retry settings "retries": 3 }`, null, { no_comments: true }) // Result is plain object without Symbol properties console.log(Object.getOwnPropertySymbols(obj).length) // 0 console.log(obj.timeout) // 5000 ``` -------------------------------- ### RangeError Example 2 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a RangeError when a non-property 'where' value is used with a key in moveComments(). ```javascript try { moveComments(obj, obj, { where: 'before-all', key: 'a' }, // Invalid: before-all with key { where: 'after-all' } ) } catch (error) { console.log(error.message) // 'Unsupported comment position before-all with key a' } ``` -------------------------------- ### Get a clean object Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Use `parse(json, null, { no_comments: true, no_blank_lines: true })` to get a clean object without comments or blank lines. ```javascript parse(json, null, { no_comments: true, no_blank_lines: true }) ``` -------------------------------- ### RangeError Example 1 Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates catching a RangeError when an invalid 'where' value is provided to moveComments() with a key. ```javascript const { moveComments } = require('comment-json') const obj = parse('{\"a\": 1}') try { moveComments(obj, obj, { where: 'invalid-position', key: 'a' }, { where: 'before', key: 'a' } ) } catch (error) { console.log(error.name) // 'RangeError' console.log(error.message) // 'Unsupported comment position invalid-position with key a' } ``` -------------------------------- ### CommentSymbol Example Usage Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/types.md Demonstrates how to use CommentDescriptor and CommentSymbol in TypeScript for type-safe access to comment properties. ```typescript import { CommentDescriptor, CommentSymbol } from 'comment-json' const descriptor: CommentDescriptor = 'before:foo' const symbol = Symbol.for(descriptor) as CommentSymbol ``` -------------------------------- ### Stringify without comments (minified) Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example of stringifying a parsed object into a compact JSON string without comments. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // comment "key": "value" }`) const compact = stringify(obj) console.log(compact) // {"key":"value"} ``` -------------------------------- ### Remove blank lines but keep comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example demonstrating parsing JSON to remove blank lines while preserving comments. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // Setting A "settingA": true, // Setting B "settingB": false }`, null, { no_blank_lines: true }) console.log(stringify(obj, null, 2)) // { // // Setting A // "settingA": true, // // Setting B // "settingB": false // } ``` -------------------------------- ### Configuration Files with Comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Example of parsing a JSON configuration file, modifying it, and saving it back while preserving comments. ```javascript // config.json with comments const config = parse(fs.readFileSync('config.json', 'utf-8')) // Modify config.debug = true // Save (comments preserved) fs.writeFileSync('config.json', stringify(config, null, 2)) ``` -------------------------------- ### When to create CommentArray explicitly Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/CommentArray.md Shows an example of explicitly creating a `CommentArray` when reassigning an array property to preserve comments. ```javascript const { CommentArray, parse, stringify } = require('comment-json') const obj = parse(`{ "list": [ // item 1 1, // item 2 2 ] }`) // Keep comments when reassigning obj.list = new CommentArray(0).concat(obj.list) console.log(stringify(obj, null, 2)) // { // "list": [ // 0, // // item 1 // 1, // // item 2 // 2 // ] // } ``` -------------------------------- ### Transform comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Example of transforming comments within JSON using moveComments and removeComments functions. ```javascript const { parse, stringify, moveComments, removeComments } = require('comment-json') const obj = parse(jsonString) moveComments(obj, obj, from, to) removeComments(obj, { where: 'before-all' }) ``` -------------------------------- ### Assignment of only non-property comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/assign.md This example demonstrates how to use `assign` with an empty array of keys to copy only the non-property comments (like 'before-all', 'after-all') from the source to the target object. ```javascript const { parse, assign, stringify } = require('comment-json') const source = parse(` // File header comment // This is important { "version": "1.0" } // Footer comment `) const target = { config: true } assign(target, source, []) console.log(stringify(target, null, 2)) // // File header comment // // This is important // { // "config": true // } // // Footer comment ``` -------------------------------- ### Validate JSON Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Use `tokenize()` to get tokens or `parse()` to catch SyntaxError for JSON validation. ```javascript tokenize() ``` ```javascript parse() ``` -------------------------------- ### Modify and preserve comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Example of modifying parsed JSON and then stringifying it back, preserving comments. ```javascript const { parse, stringify } = require('comment-json') const config = parse(configFile) config.timeout = 10000 fs.writeFileSync('config.json', stringify(config, null, 2)) ``` -------------------------------- ### Comment Storage Keys Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Examples of standardized Symbol keys used for storing comments. ```javascript Symbol.for('before-all') // Before first property Symbol.for('before:propName') // Before specific property Symbol.for('after:propName') // After property or comma Symbol.for('after-all') // After last property ``` -------------------------------- ### assign() example: Using empty 'keys' array to copy only non-property comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Illustrates using an empty array for the `keys` argument in `assign` to copy only non-property comments. ```javascript const obj = assign({ bar: 'baz' }, parsed, []) stringify(obj, null, 2) // // before all // { // "bar": "baz", // } ``` -------------------------------- ### Parse JSON with BigInt support Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Example of using a reviver function with `parse` to handle BigInt values that exceed `Number.MAX_SAFE_INTEGER`. ```javascript const { parse } = require('comment-json') const json = `{ "largeNumber": 9007199254740993, // Larger than MAX_SAFE_INTEGER "normalNumber": 42 }` const obj = parse(json, (key, value, context) => { if (context && /^[0-9]+$/.test(context.source)) { const num = Number(value) if (num > Number.MAX_SAFE_INTEGER) { return BigInt(context.source) } } return value }) console.log(obj.largeNumber) // 9007199254740993n console.log(obj.normalNumber) // 42 ``` -------------------------------- ### assign() example: Using 'keys' argument to exclude non-property comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Shows how specifying the `keys` argument in `assign` prevents non-property comments (like 'before all') from being copied. ```javascript const obj = assign({ bar: 'baz' }, parsed, ['foo']) stringify(obj, null, 2) // { // "bar": "baz", // // This is a comment // "foo": "bar" // } ``` -------------------------------- ### Sort keys Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Example of parsing a JSON string with comments, sorting its keys using `assign`, and then stringifying it back while preserving comments. ```js const parsed = parse(`{ // b "b": 2, // a "a": 1 }`) // Copy the properties including comments from `parsed` to the new object `{}` // according to the sequence of the given keys const sorted = assign( {}, parsed, // You could also use your custom sorting function Object.keys(parsed).sort() ) console.log(stringify(sorted, null, 2)) // { // // a // "a": 1, // // b // "b": 2 // } ``` -------------------------------- ### Custom type reconstruction Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md An example of using a reviver function to reconstruct custom types like points or colors from their string representations during parsing. ```javascript const { parse } = require('comment-json') const json = `{ "point": [10, 20], "color": "rgb(255, 128, 0)" }` const obj = parse(json, (key, value) => { if (key === 'point' && Array.isArray(value)) { return { x: value[0], y: value[1] } } if (key === 'color') { const match = value.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/) if (match) { return { r: +match[1], g: +match[2], b: +match[3] } } } return value }) console.log(obj.point) // { x: 10, y: 20 } console.log(obj.color) // { r: 255, g: 128, b: 0 } ``` -------------------------------- ### Parse into an object without comments and/or blank lines Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Example of parsing JSON content while removing comments and blank lines. ```javascript console.log(parse(content, null, { no_comments: true, no_blank_lines: true })) ``` -------------------------------- ### Backward compatibility: boolean shorthand Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Demonstrates the backward compatibility of the parse() function using a boolean shorthand for options. ```javascript const { parse } = require('comment-json') // These are equivalent: const a = parse(json, null, true) const b = parse(json, null, { no_comments: true }) // Both result in plain objects without comment Symbol properties ``` -------------------------------- ### Basic Usage Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Demonstrates how to parse a package.json file with comments and stringify it back, preserving the comments. ```js const { parse, stringify, assign, moveComments, removeComments, removeBlankLines } = require('comment-json') const fs = require('fs') const obj = parse(fs.readFileSync('package.json').toString()) console.log(obj.name) // comment-json stringify(obj, null, 2) // Will be the same as package.json, Oh yeah! 😆 // which will be very useful if we use a json file to store configurations. ``` -------------------------------- ### Dealing with BigInts using reviver and replacer Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Shows how to use the reviver function with the `source` parameter to parse BigInts and how to use a replacer function with `JSON.rawJSON` to stringify them correctly. ```javascript const {parse, stringify} = require('comment-json') const parsed = parse( `{"foo": 9007199254740993}`, // The reviver function now has a 3rd param that contains the string source. (key, value, {source}) => /^[0-9]+$/.test(source) ? BigInt(source) : value ) console.log(parsed) // { // "foo": 9007199254740993n // } stringify(parsed, (key, val) => typeof value === 'bigint' // Pay attention that // JSON.rawJSON is supported in node >= 21 ? JSON.rawJSON(String(val)) : value ) // {"foo":9007199254740993} ``` -------------------------------- ### Configuration file with preserved comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Illustrates how to use `comment-json` to read, update, and write configuration files while preserving comments and blank lines. ```javascript const { parse, stringify } = require('comment-json') const fs = require('fs') // Read config preserving comments function readConfig(path) { const content = fs.readFileSync(path, 'utf-8') return parse(content) // Default: preserves comments and blank lines } // Modify config while preserving comments function updateConfig(config, updates) { Object.assign(config, updates) return config } // Write config preserving comments function writeConfig(path, config) { const json = stringify(config, null, 2) // space=2 preserves comments fs.writeFileSync(path, json, 'utf-8') } const config = readConfig('config.json') config.debug = true writeConfig('config.json', config) ``` -------------------------------- ### Stringify with custom indentation Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Demonstrates stringifying JSON with custom indentation, including spaces and tabs. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // comment "a": 1 }`) // 4-space indentation const indented4 = stringify(obj, null, 4) // Tab indentation const indentedTab = stringify(obj, null, '\t') // Mixed indent (preserved up to 10 characters) const mixedIndent = stringify(obj, null, ' ') // 2 spaces ``` -------------------------------- ### Basic tokenization Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/tokenize.md Demonstrates basic tokenization of a JSON string with a block comment and logs the type and value of each token. ```javascript const { tokenize } = require('comment-json') const tokens = tokenize('{"a": 1 /* comment */}') tokens.forEach(token => { console.log(`${token.type}: ${token.value}`) }) // Output: // Punctuator: { // String: "a" // Punctuator: : // Number: 1 // BlockComment: comment // Punctuator: } ``` -------------------------------- ### Work with arrays Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Demonstrates working with arrays parsed by comment-json, specifically using the CommentArray instance to push new items while preserving comments. ```javascript const { parse, stringify, CommentArray } = require('comment-json') const obj = parse(jsonString) // obj.items is a CommentArray instance obj.items.push(newItem) // Comments are preserved ``` -------------------------------- ### Clean parsing for internal processing Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Shows how to parse JSON, removing all comments and blank lines for internal processing, effectively mimicking `JSON.parse()` but with `comment-json`'s handling of comments if present. ```javascript const { parse } = require('comment-json') // Parse removing all comments for internal processing function parseClean(jsonString) { return parse(jsonString, null, { no_comments: true, no_blank_lines: true }) } // Use standard JSON.parse() directly for same result // but comment-json handles comments if present const data = parseClean(externalApiResponse) ``` -------------------------------- ### Stringify with replacer array Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Demonstrates how to use the `stringify` function with a replacer array to include only specific fields while preserving their comments. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // name comment "name": "Bob", // email comment "email": "bob@example.com", // phone comment "phone": "555-1234" }`) // Only include specific fields with their comments const output = stringify(obj, ['name', 'email'], 2) console.log(output) // { // // name comment // "name": "Bob", // // email comment // "email": "bob@example.com" // } ``` -------------------------------- ### Safe parsing with fallback Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/errors.md Demonstrates how to safely parse JSON strings, catching and handling potential SyntaxErrors. ```javascript const { parse } = require('comment-json') let data = {} const jsonString = readFromFile() try { data = parse(jsonString) } catch (error) { if (error instanceof SyntaxError) { console.error(`JSON parse error at line ${error.line}, column ${error.column}: ${error.message}`) // Use default data or retry } else { throw error } } ``` -------------------------------- ### Error Handling - Parse Error Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Example of catching and handling potential SyntaxErrors during JSON parsing. ```javascript try { const obj = parse(jsonString) } catch (error) { if (error instanceof SyntaxError) { console.error(`Parse error at line ${error.line}: ${error.message}`) } } ``` -------------------------------- ### BigInt Values Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Example of using a reviver function during parsing to convert numeric strings to BigInt. ```javascript const obj = parse(json, (key, value, {source}) => /^[0-9]+$/.test(source) ? BigInt(source) : value ) ``` -------------------------------- ### Remove comment before property Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/removeComments.md This example demonstrates how to remove a comment that appears before a specific property in a JSON object. ```javascript const { parse, stringify, removeComments } = require('comment-json') const obj = parse(`{ // comment before foo "foo": 1, // comment after foo "bar": 2 }`) // Remove comment before 'foo' removeComments(obj, { where: 'before', key: 'foo' }) console.log(stringify(obj, null, 2)) // { // "foo": 1, // comment after foo // "bar": 2 // } ``` -------------------------------- ### ParseOptions Interface Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Defines the structure for configuration options when parsing JSON with comments. ```typescript interface ParseOptions { no_comments?: boolean no_blank_lines?: boolean } ``` -------------------------------- ### Remove non-property comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/removeComments.md This example shows how to remove comments that are not associated with any specific property, such as top-level or bottom-level comments. ```javascript const { parse, stringify, removeComments } = require('comment-json') const obj = parse(` // top comment { "foo": 1 } // bottom comment`) // Remove top comment removeComments(obj, { where: 'before-all' }) // Remove bottom comment removeComments(obj, { where: 'after-all' }) console.log(stringify(obj, null, 2)) // { // "foo": 1 // } ``` -------------------------------- ### Stringify with BigInt using rawJSON Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/stringify.md Shows how to stringify BigInt values using JSON.rawJSON in Node.js v21+. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ "bignum": 12345678901234567890 }`) // Convert to BigInt in replacer, then use JSON.rawJSON in node >= 21 const result = stringify(obj, (key, val) => { if (typeof val === 'bigint') { return JSON.rawJSON(String(val)) } return val }, 2) ``` -------------------------------- ### Error Handling - Comment Manipulation Error Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Example of catching and handling potential TypeErrors or RangeErrors during comment manipulation. ```javascript try { moveComments(obj, obj, from, to) } catch (error) { if (error instanceof TypeError) { console.error(`Invalid argument: ${error.message}`) } else if (error instanceof RangeError) { console.error(`Invalid position: ${error.message}`) } } ``` -------------------------------- ### Basic parse and stringify Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Basic usage of parse and stringify functions to parse JSON with comments and stringify it back while preserving comments. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(jsonString) console.log(stringify(obj, null, 2)) // Preserves comments ``` -------------------------------- ### Remove multiple property comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/removeComments.md This example illustrates removing multiple types of comments associated with a property, including comments before the property and after its value. ```javascript const { parse, stringify, removeComments } = require('comment-json') const obj = parse(`{ // property comment "key": 1, // inline comment // another "key2": 2 }`) removeComments(obj, { where: 'before', key: 'key' }) removeComments(obj, { where: 'after-value', key: 'key' }) console.log(stringify(obj, null, 2)) // { // "key": 1, // // another // "key2": 2 // } ``` -------------------------------- ### Basic stringify with comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/stringify.md Demonstrates basic stringification of a parsed JSON object, preserving comments and indentation. ```javascript const { parse, stringify } = require('comment-json') const json = `{ // Important setting "timeout": 5000, // milliseconds "enabled": true }` const obj = parse(json) const output = stringify(obj, null, 2) console.log(output) // { // // Important setting // "timeout": 5000, // milliseconds // "enabled": true // } ``` -------------------------------- ### Remove all comments of a specific position Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/removeComments.md This example demonstrates removing all comments that appear after a property's value for a specific property within a nested object. ```javascript const { parse, stringify, removeComments } = require('comment-json') const config = parse(`{ "database": { "host": "localhost", // DB host "port": 5432 // DB port } }`) // Remove all 'after-value' comments from the root object removeComments(config, { where: 'after-value', key: 'database' }) console.log(stringify(config, null, 2)) ``` -------------------------------- ### Transform date strings during parsing Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/configuration.md Shows how to use a reviver function to transform date strings into JavaScript `Date` objects during parsing. ```javascript const { parse } = require('comment-json') const json = `{ "created": "2024-01-15T10:30:00Z", "updated": "2024-01-20T14:45:00Z" }` const obj = parse(json, (key, value) => { if (key.includes('date') || key.includes('created') || key.includes('updated')) { return new Date(value) } return value }) console.log(obj.created instanceof Date) // true ``` -------------------------------- ### Tokenize with range information Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/tokenize.md Tokenizes a JSON string with range information and extracts a line comment using its start and end character indices. ```javascript const { tokenize } = require('comment-json') const json = '{"a": 1 // comment' const tokens = tokenize(json, { range: true }) const commentToken = tokens.find(t => t.type === 'LineComment') if (commentToken) { const start = commentToken.range[0] const end = commentToken.range[1] console.log(json.substring(start, end)) // // comment } ``` -------------------------------- ### Module Architecture Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Overview of the module's file structure and their responsibilities. ```plaintext src/index.js Entry point, exports all functions src/parse.js Tokenization, parsing, comment tracking src/stringify.js Serialization with comment reconstruction src/array.js CommentArray implementation src/common.js Shared utilities, comment manipulation ``` -------------------------------- ### Using reviver with source context Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/parse.md Demonstrates the use of the `reviver` function to transform parsed values. The `context.source` property provides the raw string source of the value, allowing for conditional transformations like converting large numbers to BigInt. ```javascript const { parse } = require('comment-json') const json = `{"bigint": 9007199254740993}` const result = parse(json, (key, value, context) => { if (context && /^[0-9]+$/.test(context.source)) { return BigInt(context.source) } return value }) console.log(result.bigint) // 9007199254740993n ``` -------------------------------- ### Basic Usage Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/README.md Demonstrates how to parse JSON with comments, modify the resulting object, and stringify it back while preserving comments. ```javascript const { parse, stringify } = require('comment-json') // Parse JSON with comments const obj = parse(`{ // Configuration "timeout": 5000, // milliseconds "retries": 3 }`) // Modify obj.timeout = 10000 // Save with comments preserved console.log(stringify(obj, null, 2)) ``` -------------------------------- ### Handle BigInt values Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Use `parse()` with a reviver function to handle BigInt values. ```javascript parse() ``` -------------------------------- ### Moving comments between different objects Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Shows how to move a comment from a source object to a target object using `moveComments`. ```javascript const source = parse(`{ "foo": 1 // source comment }`) const target = { bar: 2 } // Move comment from source to target moveComments(source, target, { where: 'after-value', key: 'foo' }, { where: 'before', key: 'bar' } ) console.log(stringify(target, null, 2)) // { // // source comment // "bar": 2 // } ``` -------------------------------- ### Append vs override comments (Append) Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/moveComments.md Demonstrates the default behavior of appending comments when moving them to a target location that already has comments, with `override` set to `false`. ```javascript const { parse, stringify, moveComments } = require('comment-json') const obj = parse(`{ // existing comment "foo": 1, // another comment "bar": 2 }`) // Append (default behavior) moveComments(obj, obj, { where: 'after-value', key: 'foo' }, { where: 'before', key: 'foo' }, false ) console.log(stringify(obj, null, 2)) // { // // existing comment // // another comment // "foo": 1, // "bar": 2 // } ``` -------------------------------- ### Custom tokenization without comments Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/tokenize.md Compares tokenization results with and without comment tokens included, showing the difference in the number of tokens. ```javascript const { tokenize } = require('comment-json') const json = '{"a": 1 /* comment */ }' // Tokenize with comments const withComments = tokenize(json, { comment: true }) console.log(withComments.length) // Includes comment tokens // Tokenize without comments (for compatibility) const withoutComments = tokenize(json, { comment: false }) console.log(withoutComments.length) // Only JSON tokens ``` -------------------------------- ### Stringify with replacer array Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/stringify.md Demonstrates stringifying a JSON object using a replacer array to include only specified properties. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // Author name "name": "Bob", // Author email "email": "bob@example.com", // Internal ID "id": 42 }`) const output = stringify(obj, ['name', 'email'], 2) // Only 'name' and 'email' are included with their comments ``` -------------------------------- ### Query comments in TypeScript Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Demonstrates how to use `CommentSymbol` and `CommentDescriptor` to query comments associated with JSON properties in TypeScript. ```typescript import { CommentDescriptor, CommentSymbol, parse, CommentArray } from 'comment-json' const parsed = parse(`{ /* test */ "foo": "bar" }`) // typescript only allows properly formatted symbol names here const symbolName: CommentDescriptor = 'before:foo' console.log((parsed as CommentArray)[Symbol.for(symbolName) as CommentSymbol][0].value) ``` -------------------------------- ### Sorting JSON Keys Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Demonstrates how to sort JSON keys alphabetically using the assign function. ```javascript const parsed = parse(json) const sorted = assign({}, parsed, Object.keys(parsed).sort()) ``` -------------------------------- ### Modify and save Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Read a config file, modify it, and write it back, preserving comments and formatting. ```javascript const config = parse(fs.readFileSync('config.json', 'utf-8')) config.timeout = 10000 fs.writeFileSync('config.json', stringify(config, null, 2)) ``` -------------------------------- ### stringify() signature Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md The signature for the `stringify` function, which is similar to the native `JSON.stringify` but handles comments. ```typescript stringify(object: any, replacer?, space?): string ``` -------------------------------- ### Stringify without comments (compact) Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/stringify.md Shows how to stringify a JSON object without comments by omitting the 'space' parameter. ```javascript const { parse, stringify } = require('comment-json') const obj = parse(`{ // comment "key": "value" }`) const compact = stringify(obj) // No space parameter console.log(compact) // {"key":"value"} ``` -------------------------------- ### assign() method signature Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md The signature for the `assign` method, used for copying properties and their associated comments. ```javascript assign(target: object, source?: object, keys?: Array) ``` -------------------------------- ### TokenizeOptions Interface Definition Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/types.md Defines the configuration options for the tokenize() function. ```typescript interface TokenizeOptions { tolerant?: boolean range?: boolean loc?: boolean comment?: boolean } ``` -------------------------------- ### Accessing and using CommentArray Source: https://github.com/kaelzhang/node-comment-json/blob/master/README.md Shows how to access the `CommentArray` constructor and how modifying a `CommentArray` preserves its comments. ```javascript const {CommentArray} = require('comment-json') const parsed = parse(`{ "foo": [ // bar "bar", // baz, "baz" ] }`) parsed.foo.unshift('qux') stringify(parsed, null, 2) // { // "foo": [ // "qux", // // bar // "bar", // // baz // "baz" // ] // } ``` -------------------------------- ### Work with arrays Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Use CommentArray methods (splice, slice, etc.) to preserve comments when working with arrays. ```javascript CommentArray ``` -------------------------------- ### Append vs override comments (Override) Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/moveComments.md Demonstrates overriding existing comments when moving them to a target location by setting the `override` parameter to `true`. ```javascript // Override existing comments moveComments(obj, obj, { where: 'before', key: 'bar' }, { where: 'before', key: 'foo' }, true // override = true ) console.log(stringify(obj, null, 2)) // { // // bar comment // // another comment // "foo": 1, // "bar": 2 // } ``` -------------------------------- ### Sort JSON keys Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/api-reference/overview.md Use `assign({}, parsed, Object.keys(parsed).sort())` to sort JSON keys. ```javascript assign({}, parsed, Object.keys(parsed).sort()) ``` -------------------------------- ### Exports Summary Source: https://github.com/kaelzhang/node-comment-json/blob/master/_autodocs/INDEX.md Lists the main functions and constants exported by the comment-json library. ```javascript const { parse, stringify, tokenize, CommentArray, assign, moveComments, removeComments, removeBlankLines, // Constants PREFIX_BEFORE, PREFIX_AFTER_PROP, PREFIX_AFTER_COLON, PREFIX_AFTER_VALUE, PREFIX_AFTER, PREFIX_BEFORE_ALL, PREFIX_AFTER_ALL } = require('comment-json') ```