{"_id":"jsonc@3.0.0","bugs":{"url":"https://github.com/onury/jsonc/issues"},"dist":{"shasum":"d731f9b4a63c6d95300dedc0682d18393a254f0c","tarball":"http://registry-npm.ywwl.com/jsonc/download/jsonc-3.0.0.tgz","fileCount":23,"integrity":"sha512-hfb1qUb/sxI0jU6cAw5nxyGDbbuWv4ay2yYziRlkkagiRXAJeiRpw/LyNoGergmizqi7m604IoAF7Hi6jV/Jwg==","signatures":[{"sig":"MEUCIELSE/OA9hb0iEDEr1uCUfwaYK7xSOJMILWnLAY2Xpz5AiEAvDTpH1uuZkLnG8kgAiciehSA/V3/YY1tmOHUhjLiXbU=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCFl834dM7pLPvDVh/AMcIuGljq2Jw17iEKVx9G9SVOFAIgLZG68Eu0wtKzirN3AAfBot65lgubJ1vZJZjEtjPYOB8="}],"unpackedSize":72815,"size":17797,"noattachment":false,"key":"/jsonc/-/jsonc-3.0.0.tgz"},"main":"./lib/index.js","name":"jsonc","type":"module","types":"./lib/index.d.ts","author":{"name":"Onur Yıldırım","email":"onur@cutepilot.com"},"module":"./lib/index.js","engines":{"node":">=22"},"exports":{".":{"types":"./lib/index.d.ts","import":"./lib/index.js","default":"./lib/index.js"},"./package.json":"./package.json"},"gitHead":"02eb679a501ead29166ba42817de499c5c8b0a62","license":"MIT","scripts":{"lint":"biome check src test","test":"vitest run","build":"tsc -p tsconfig.build.json","cover":"vitest run --coverage","format":"biome check --write src test","pretest":"npm run lint && npm run typecheck","mutation":"stryker run","typecheck":"tsc --noEmit -p tsconfig.json","prepublishOnly":"npm run build"},"version":"3.0.0","_npmUser":{"name":"onury","email":"onur@cutepilot.com"},"homepage":"https://github.com/onury/jsonc#readme","keywords":["json","jsonc","comments","parse","stringify","circular","cyclic","safe","read-file","write-file","strip-comments","bom","log","uglify","beautify","minify","typescript","esm"],"overrides":{"qs":"^6.16.0"},"repository":{"url":"git+https://github.com/onury/jsonc.git","type":"git"},"_npmVersion":"11.16.0","description":"Everything you need in JSON land. Parse JSON with comments, stringify objects with circular references, etc...","directories":{},"maintainers":[{"name":"onury","email":"onur@cutepilot.com"}],"sideEffects":false,"_nodeVersion":"24.18.1","dependencies":{"parse-json":"^8.3.0","fast-safe-stringify":"^2.1.1","strip-json-comments":"^5.0.3"},"_hasShrinkwrap":false,"devDependencies":{"vitest":"^4.1.11","typescript":"^6.0.3","@types/node":"^26.6.2","tsconfig-oy":"^2.0.1","@biomejs/biome":"^2.5.14","biome-config-oy":"^1.1.0","@stryker-mutator/core":"^10.0.0","@vitest/coverage-istanbul":"^4.1.11","@stryker-mutator/vitest-runner":"^10.0.0"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/jsonc_3.0.0_1790206979420_0.46992245870184424"},"readme":"# jsonc\n\n<p align=\"center\">\n  <a href=\"https://github.com/onury/jsonc/actions/workflows/ci.yml\"><img src=\"https://github.com/onury/jsonc/actions/workflows/ci.yml/badge.svg\" alt=\"build\" /></a>\n  <a href=\"#tests--quality\"><img src=\"https://img.shields.io/badge/coverage-100%25-2BB150?logo=vitest&logoColor=%23FDC72B&style=flat\" alt=\"coverage\" /></a>\n  <a href=\"https://stryker-mutator.io/docs/\"><img src=\"https://img.shields.io/badge/mutation-100%25-2BB150?style=flat\" alt=\"mutation score\" /></a>\n  <a href=\"https://www.npmjs.com/package/jsonc\"><img src=\"https://img.shields.io/npm/v/jsonc.svg?style=flat&label=&color=%23C6234B&logo=npm\" alt=\"version\" /></a>\n  <a href=\"https://www.npmjs.com/package/jsonc\"><img src=\"https://img.shields.io/npm/dm/jsonc.svg?style=flat&color=2BB150&label=downloads\" alt=\"downloads\" /></a>\n  <a href=\"https://gist.github.com/onury/d3f3d765d7db2e8b2d050d14315f2ac7\"><img src=\"https://img.shields.io/badge/ESM-F7DF1E?style=flat\" alt=\"ESM\" /></a>\n  <a href=\"https://www.typescriptlang.org/\"><img src=\"https://img.shields.io/badge/TS-3260C7?style=flat\" alt=\"TS\" /></a>\n  <a href=\"https://github.com/onury/jsonc/blob/master/LICENSE\"><img src=\"https://img.shields.io/npm/l/jsonc.svg?style=flat&color=blue\" alt=\"license\" /></a>\n</p>\n\n> This module is **ESM** 🔆. Please [**read this**](https://gist.github.com/onury/d3f3d765d7db2e8b2d050d14315f2ac7).\n\nEverything you need in JSON land. Parse JSON with comments, stringify objects with circular references, read and write JSON files; and do all of it safely, without try/catch blocks if you like.\n\n```sh\nnpm i jsonc\n```\n\n## Features\n\n- Parse JSON with **comments** (and optionally, **trailing commas**).\n- Stringify objects with **circular** references.\n- **Safely** parse / stringify without try/catch blocks.\n- **Read** and auto-parse JSON files, sync or async (with promises).\n- Auto-stringify and **write** JSON files, sync or async; creates missing directories.\n- Strips the UTF-8 **BOM**.\n- **Log** objects as JSON, without worrying about errors.\n- **Uglify** / **beautify** JSON strings.\n- More helpful JSON **errors** (via [parse-json][parse-json]).\n- **Typed**. Written in TypeScript.\n\n## Usage\n\n```ts\nimport { jsonc } from 'jsonc';\n// or the default export\nimport jsonc from 'jsonc';\n\n// CommonJS (Node.js 22.12 or newer)\nconst jsonc = require('jsonc');\n```\n\nThis is safe for JSON with comments:\n\n```ts\njsonc.parse('// comment\\n{\"data\": /* comment */ \"value\"}\\n'); // —> { data: 'value' }\n```\n\nAnd this is safe for circular references:\n\n```ts\nconst obj = { x: 1 };\nobj.y = obj; // circular\njsonc.stringify(obj); // —> '{\"x\":1,\"y\":\"[Circular]\"}'\n```\n\nBut this is seriously safe:\n\n```ts\n// safe version of every method\nimport { safe as jsonc } from 'jsonc';\n\nconst [err, result] = jsonc.parse('[invalid JSON}');\nif (err) {\n  console.log(`Failed to parse JSON: ${err.message}`);\n} else {\n  console.log(result);\n}\n```\n\n> [!NOTE]\n> Since v3 this package is ESM-only. CommonJS code can still `require()` it on Node.js 22.12 or newer (Node's `require(esm)`), and it returns `jsonc` itself as v2 did; so `const jsonc = require('jsonc')` and `const { jsonc, safe } = require('jsonc')` both work. On Node.js 22.0 – 22.11, use `import` or `await import('jsonc')`.\n\n### Parse & Stringify\n\n`parse()` strips comments before parsing. It takes the native reviver function, or an options object. Comments are replaced with whitespace, so the position in a parse error points into your original string.\n\n```ts\njsonc.parse('{\"a\":1} // one', (key, value) => (key === 'a' ? 2 : value)); // —> { a: 2 }\njsonc.parse(str, { stripComments: false }); // throws if str has comments\n\n// trailing commas are opt-in (as in tsconfig.json)\njsonc.parse('{ \"a\": [1, 2,], }', { allowTrailingCommas: true }); // —> { a: [1, 2] }\n\n// typed result (not validated at runtime)\nconst config = jsonc.parse<IConfig>(str);\n```\n\n`stringify()` supports both the native `JSON.stringify()` signature and an options object. Circular references are replaced with `\"[Circular]\"` unless you turn it off with `handleCircular: false`; in which case it throws like the native method. Anything else the native method throws for (a `BigInt`, a throwing `toJSON()`, etc…) is thrown as well.\n\n```ts\njsonc.stringify(obj, null, 2);\njsonc.stringify(obj, { replacer: ['a', 'b'], space: 2 });\njsonc.stringify(obj, { handleCircular: false }); // throws if obj has circular references\n```\n\n### Validate, Strip, Uglify & Beautify\n\n```ts\njsonc.isJSON('{\"x\":1}');                 // —> true\njsonc.isJSON('true');                    // —> false (valid JSON but no object or array structure)\njsonc.isJSON('// c\\n{\"x\":1}', true);     // —> true (allow comments)\n\njsonc.stripComments('// c\\n{\"x\":1}');    // —> '\\n{\"x\":1}'\njsonc.uglify('{\\n  // c\\n  \"x\": 1\\n}');  // —> '{\"x\":1}'\njsonc.beautify('{\"x\":1}');               // —> '{\\n  \"x\": 1\\n}'\njsonc.normalize(new SomeClass());        // —> plain object\n```\n\n### Read & Write Files\n\n`read()` strips the UTF-8 BOM and comments, then parses; it takes the same `allowTrailingCommas` option. `write()` stringifies the same way `stringify()` does (circular references included, unless `handleCircular` is `false`), adds a trailing newline and creates missing parent directories (unless `autoPath` is `false`).\n\n```ts\nconst config = await jsonc.read<IConfig>('path/to/config.json');\nawait jsonc.write('path/to/out.json', config, { space: 2 });\n\n// sync versions\nconst data = jsonc.readSync('path/to/config.json');\njsonc.writeSync('path/to/out.json', data);\n```\n\nWith the safe versions, the returned promise never rejects:\n\n```ts\nimport { safe as jsonc } from 'jsonc';\n\nconst [err, config] = await jsonc.read('path/to/config.json');\nif (err) console.log('Failed to read JSON file');\n```\n\n### Logging\n\n`log()` and `logp()` (pretty) stringify their arguments without throwing and write them to `process.stdout`. An `Error` is logged with its stack, to `process.stderr`. Use `config()` to redirect either stream.\n\n```ts\njsonc.log({ a: 1 }, [1, 2]); // {\"a\":1} [1,2]\njsonc.logp({ a: 1 });\n// {\n//   \"a\": 1\n// }\n\njsonc.config({ streamErr: fs.createWriteStream('errors.log') });\njsonc.log(new Error('this is logged to the file'));\n```\n\n## API\n\nAll methods are static; `jsonc.safe` (also the named `safe` export) holds the safe versions.\n\n| Method | Returns | Safe version returns | Description |\n| ------ | ------- | -------------------- | ----------- |\n| `parse<T>(str, options?)` | `T` (default `any`) | `[err, T]` | Parses a JSON string; comments are stripped. `options` is a reviver function or [parse options](#options). |\n| `stringify(value, options?)`<br/>`stringify(value, replacer?, space?)` | `string` | `[err, string]` | Stringifies a value. `options` are the [stringify options](#options). Throws for circular references only if `handleCircular` is `false`, and for anything the native method throws for (e.g. a `BigInt`). |\n| `isJSON(str, allowComments?)` | `boolean` | `boolean` | Whether the string is JSON with an object or array structure. `allowComments` defaults to `false`. |\n| `stripComments(str, whitespace?)` | `string` | `[err, string]` | Strips comments; or replaces them with whitespace when `whitespace` is `true`. |\n| `uglify(str)` | `string` | `[err, string]` | Removes comments and whitespace from a JSON string. |\n| `beautify(str, space?)` | `string` | `[err, string]` | Removes comments and indents a JSON string. `space` defaults to `2`. |\n| `normalize<T>(value, replacer?)` | `T` (default `any`) | `[err, T]` | Stringifies and parses back a value, to plain JSON data. |\n| `read<T>(filePath, options?)` | `Promise<T>` | `Promise<[err, T]>` | Reads and parses a JSON file; strips the UTF-8 BOM. `options` are the [parse options](#options). |\n| `readSync<T>(filePath, options?)` | `T` | `[err, T]` | Sync version of `read()`. |\n| `write(filePath, data, options?)` | `Promise<true>` | `Promise<[err, true]>` | Stringifies and writes a JSON file, with a trailing newline. `options` are the [write options](#options). |\n| `writeSync(filePath, data, options?)` | `true` | `[err, true]` | Sync version of `write()`. |\n| `log(...args)` | `void` | `void` | Logs the arguments as JSON. |\n| `logp(...args)` | `void` | `void` | Logs the arguments as indented JSON. |\n| `config(cfg?)` | `void` | `void` | Sets `{ stream?, streamErr? }` for the loggers. Omitted streams reset to `process.stdout` / `process.stderr`. |\n\n### Options\n\n| Option | Type | Default | Used by | Description |\n| ------ | ---- | ------- | ------- | ----------- |\n| `reviver` | `Reviver` | — | parse, read, readSync | Transforms the parsed results, as with `JSON.parse()`. |\n| `stripComments` | `boolean` | `true` | parse, read, readSync | Whether to strip comments. If `false`, comments are a parse error. |\n| `allowTrailingCommas` | `boolean` | `false` | parse, read, readSync | Whether to allow trailing commas in objects and arrays. Takes effect only when comments are stripped. |\n| `replacer` | `Replacer` | — | stringify, write, writeSync | A replacer function, or an allow-list array of property names. |\n| `space` | `string \\| number` | — | stringify, write, writeSync | Indentation; a number of spaces or an indent string. |\n| `handleCircular` | `boolean` | `true` | stringify, write, writeSync | Whether to replace circular references with `\"[Circular]\"`. If `false`, they throw. |\n| `mode` | `number` | `0o666` | write, writeSync | File-system permission mode for a new file. |\n| `autoPath` | `boolean` | `true` | write, writeSync | Whether to create missing parent directories. |\n\nExported types: `IParseOptions`, `IStringifyOptions`, `IReadOptions`, `IWriteOptions`, `IConfig`, `Replacer`, `Reviver`, `SafeResult<T>`.\n\n## Tests & Quality\n\n100% test coverage (statements, branches, functions, lines) and a **100% [Stryker](https://stryker-mutator.io) mutation score**, run across Node.js 22, 24 and 26 in CI.\n\n## Changelog\n\nSee [**CHANGELOG.md**][changelog]. **v3 is ESM-only** and requires Node.js 22 or newer; it also changes a few behaviors (circular references in `write()`, `BigInt` in `stringify()`, parse error positions). The migration notes live there.\n\n## Related Projects\n\n- [**notation**](https://github.com/onury/notation) — Read, modify, and filter the contents of objects and arrays via dot/bracket notation strings or glob patterns.\n\n## License\n\n© 2026, Onur Yıldırım. [**MIT**][license] License.\n\n[license]:https://github.com/onury/jsonc/blob/master/LICENSE\n[changelog]:https://github.com/onury/jsonc/blob/master/CHANGELOG.md\n[parse-json]:https://github.com/sindresorhus/parse-json\n","publish_time":1790206979706,"_cnpm_publish_time":1790206979706,"dist-tags":{"latest":"3.0.0"}}