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-writerVerified import paths — ran on the pinned version, not inferred.
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.
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' })`.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.
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.
Install `jscodeshift` as a dependency: `npm install jscodeshift` or `yarn add jscodeshift`.
For CommonJS, use `const json5Writer = require('json5-writer');` then `json5Writer.load()`. For ESM, use `import json5Writer from 'json5-writer';` then `json5Writer.load()`.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.