This is especially useful for making programmatic changes to JSON config files.
Install
Deno:
deno add jsr:@david/jsonc-morph
Or with npm:
npm install jsonc-morph
Example
import { parse, parseToValue } from "@david/jsonc-morph";// parse directly to a plain JavaScript valueconst config = parseToValue(`{ // database settings "host": "localhost", "port": 5432}`);console.log(config.host); // "localhost"console.log(config.port); // 5432// parse to a CST for programmatic editingconst root = parse(`{ // 1 "data" /* 2 */: 123 // 3} // 4`);// get the root objectconst rootObj = root.asObjectOrThrow();// set its "data" property to have a new value
Options and strict parsing
By default, parse and parseToValue allow more than just JSONC (comments,
trailing commas, single-quoted strings, hexadecimal numbers, etc.). You can
customize this behaviour by passing options:
import { parse, parseToValue } from "@david/jsonc-morph";// disable specific extensionsconst root = parse(text, { allowComments: false, // reject // and /* */ comments allowTrailingCommas: false, // reject trailing commas in arrays/objects allowSingleQuotedStrings: false, // reject 'single quoted' strings allowHexadecimalNumbers: false, // reject 0xFF style numbers allowUnaryPlusNumbers: false, // reject +42 style numbers allowBareDecimalPointNumbers: false, // reject .5 and 5. style numbers allowNonFiniteNumbers: false, // reject Infinity, -Infinity and NaN allowExtendedStringEscapes: false, // reject JSON5 escapes like \x41 and \v allowMissingCommas: false, // reject missing commas between elements
For strict JSON parsing (only allow JSON), use parseStrict or
parseToValueStrict:
import { parseStrict, parseToValueStrict } from "@david/jsonc-morph";// all extensions disabled by defaultconst root = parseStrict('{"name": "test"}');// selectively enable specific extensionsconst rootWithComments = parseStrict(text, { allowComments: true });// same for `parseToValueStrict`const value = parseToValueStrict('{"name": "test"}');