Registry / serialization / json5-writer

json5-writer

JSON →
library0.2.0jsnpmunverified

json5-writer is a JavaScript utility designed to parse and modify JSON and JSON5 files while meticulously preserving comments, whitespace, and original formatting. Unlike typical JSON parsers that discard non-data elements, this library converts JSON5 input into a JavaScript Abstract Syntax Tree (AST) using jscodeshift, allowing programmatic updates to values without disturbing surrounding comments or formatting. It is particularly useful for configuration file management where human-readable comments are critical. The current stable version is 0.2.0. The package does not explicitly state its release cadence, but its unique AST-based approach provides fine-grained control over output, distinguishing it from simpler JSON modification tools. It supports both JSON and JSON5 syntax for input and can output standard JSON or JSON5 with configurable options for quoting and trailing commas.

npm install json5-writer
INSTALL
IMPORT
SIG · JSON5-WRITER
J
json5-writer
serializationjavascriptv0.2.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

json5Writer
import json5Writer from 'json5-writer';
const json5Writer = require('json5-writer').default;
While the README uses `require('json5-writer')` for CommonJS, modern Node.js and bundlers often resolve this to a default import. For direct CommonJS usage, `const json5Writer = require('json5-writer');` is correct. The import shown here is for ESM.
json5Writer.load
import json5Writer from 'json5-writer'; const writer = json5Writer.load(jsonStr);
import { load } from 'json5-writer';
`load` is a method on the default export object, not a named export itself.
j
import j from 'jscodeshift';
const j = require('jscodeshift').j;
jscodeshift's main export is often referred to as `j` by convention in its examples for AST traversal. This is a default import for jscodeshift itself, used for direct AST manipulation.

This quickstart demonstrates loading, modifying, and saving a JSON5 configuration file, preserving comments and formatting. It shows how to update existing properties, add new ones, and use `undefined` to explicitly retain a property's value when writing a new object, using environment variables for dynamic values.

import * as fs from 'node:fs/promises'; import * as path from 'node:path'; import json5Writer from 'json5-writer'; async function updateConfigFile() { const configPath = path.join(process.cwd(), 'config.json5'); const initialConfig = `{ // Main application settings 'app-name': 'My Awesome App', // Database connection details db: { host: 'localhost', port: 5432, user: 'admin' }, // Feature flags features: { beta: true, analytics: false } }`; // Ensure config file exists for demonstration await fs.writeFile(configPath, initialConfig, 'utf-8'); try { const configContent = await fs.readFile(configPath, 'utf-8'); const writer = json5Writer.load(configContent); writer.write({ 'app-name': 'New App Name', db: { host: process.env.DB_HOST ?? 'prod.database.com', // Use env var or default // 'port' will be preserved if not explicitly overwritten with undefined or a new value user: 'deploy_user' // Update user }, features: { beta: undefined, // Preserve existing 'beta' value analytics: true, // Update analytics flag 'new-feature': true // Add a new feature } }); const updatedConfigContent = writer.toSource({ quote: 'single', trailingComma: true, quoteKeys: undefined }); console.log('Updated config.json5 content:\n', updatedConfigContent); await fs.writeFile(configPath, updatedConfigContent, 'utf-8'); console.log(`Successfully updated ${configPath}`); } catch (error) { console.error(`Failed to update config file: ${error.message}`); } } updateConfigFile();
Debug
Known issues
gotchaWhen using the `.write(value)` method, any property or field present in the original document but not in the `value` object passed to `.write()` will be removed. To explicitly preserve an existing value while updating other fields, you must set its corresponding property in the `value` object to `undefined`.
fix
Pass `undefined` for properties you wish to retain from the original document but not modify with the current `.write()` call. For example, `writer.write({ propertyToKeep: undefined, otherProperty: 'newValue' })`.
affects: >=0.1.0
gotchaThe default output options for `.toSource()` (which outputs JSON5) and `.toJSON()` (which outputs standard JSON) differ. `.toSource()` by default uses single quotes, trailing commas, and infers key quoting, whereas `.toJSON()` defaults to double quotes, no trailing commas, and quotes all keys.
fix
Always explicitly specify options for `quote`, `trailingComma`, and `quoteKeys` in both `.toSource()` and `.toJSON()` if you require a consistent or specific output format across different calls or when converting between JSON5 and JSON.
affects: >=0.1.0
gotchaAdvanced manipulation of the parsed document requires direct interaction with the underlying jscodeshift AST via the `.ast` property. This necessitates familiarity with jscodeshift's API and AST structures, which can have a learning curve.
fix
Consult the `jscodeshift` documentation for AST node types and traversal methods. Start with simple `find` and `forEach` operations to understand the AST structure before attempting complex transformations.
affects: >=0.1.0
Errors
Common errors & fixes
Error: Cannot find module 'jscodeshift'
The `jscodeshift` package is a peer dependency or a required runtime dependency for `json5-writer`'s core functionality and must be installed separately.
fix
Install `jscodeshift` as a dependency: `npm install jscodeshift` or `yarn add jscodeshift`.
TypeError: writer.load is not a function
Incorrect import of `json5-writer`. The library exports a default object, and `load` is a method on that object.
fix
For CommonJS, use `const json5Writer = require('json5-writer');` then `json5Writer.load()`. For ESM, use `import json5Writer from 'json5-writer';` then `json5Writer.load()`.
SyntaxError: Unexpected token / in JSON at position X
Attempting to parse a JSON5 string (which allows comments) with the native `JSON.parse()` method before passing it to `json5-writer`, or when `.toJSON()` is expected but comments are still present.
fix
Ensure you are passing the raw JSON5 string directly to `json5Writer.load()`. If outputting JSON, use `.toJSON()` and verify comments are stripped, or ensure no comments are added if the target system only accepts strict JSON.
Upgrade
Version history
0.2.0latest on npm
Audit
Dependencies
jscodeshiftrequiredCore dependency for AST manipulation and transformation; advanced usage directly exposes its API.
Agent activity
8 hits · last 30 days
node
8
Resources
json5-writer — npm install json5-writer · libregistry