Editing JSON5 Without Losing Comments

Change one value, keep every comment and every space.

Comments are the reason many teams choose JSON5, and the first script that rewrites the file with parse and stringify deletes all of them. The standard parsers throw comments away on purpose, because they are not data.

This guide shows what is lost, then runs six libraries on one commented file in JavaScript and Python, compares what each preserves, and gives recipes for bumping a version, adding a key and updating an array.

A config file on a desk where a stamp changes one value and every comment stays in place

What you will learn: The reference json5 package cannot write comments back, so a script that edits a file through it deletes every comment. A comment-preserving editor keeps the original text and changes only the part you touch. We ran @croct/json5-parser, json5-trueformat, golden-fleece, json5-writer, jsonc-parser and Python's json-five on the same file; the real output is below. Do not point jsonc-parser at a JSON5 file.

Comment icon

Why Comments and Formatting Vanish

A normal parser turns text into data, and data has no place to keep a comment. JSON5.parse returns plain objects, arrays, strings and numbers, so the comments, the blank lines, the quote style and the trailing commas are gone before your code sees the result. Writing the object back out can only produce a fresh, machine-formatted document.

Here is the loss with the reference library, version 2.2.3, on the file shown in the next section. The script bumps the version and calls stringify:

const JSON5 = require('json5'); const obj = JSON5.parse(fs.readFileSync('app.json5', 'utf8')); obj.version = '1.3.0'; console.log(JSON5.stringify(obj, null, 2));
{ version: '1.3.0', ports: [ 8080, 8081, ], features: { darkMode: true, beta: false, }, name: 'demo-app', }

All four comments are gone, the compact ports array was exploded onto separate lines, and the file header vanished. The data is correct, but a code review of that change would show a rewrite of the whole file. Python's json5 package behaves the same way: dumps writes the data, not the comments.

Maintainers know about this limit. A 2018 request titled "Options for preserving comments when editing a JSON5 file by script" (issue #177 on the reference repository) was closed in April 2020 after the maintainer said the parser would stay a reference implementation and gain no new features. Issue #122, "Generate JSON5", is still open. The practical answer is a different kind of parser.

The idea that fixes it: keep the text

Tools that preserve comments build a concrete syntax tree or an edit list instead of plain data. Every token keeps its original whitespace and comments, so printing an unmodified tree gives back the exact input, byte for byte. An edit then replaces one node, or one character range, and everything else is copied through. The libraries below differ in how they expose that tree, and in how well they place comments when you add, delete or move things.

Test icon

The Test File

Every sample on this page edits this file, saved as app.json5 with Unix (LF) line endings. It uses the features that editors most often damage: a file header, a block comment, trailing comments, single-quoted strings, unquoted keys and trailing commas.

// Application settings { // semantic version, bumped by the release script version: '1.2.0', /* ports the dev server may use */ ports: [8080, 8081], // keep sorted features: { darkMode: true, // shipped in 1.1 beta: false, }, name: 'demo-app', }

The edits we make are the three everyday ones: change version to '1.3.0', append 8082 to ports, and add keys (features.telemetry and a top-level region). A good result changes exactly those lines and leaves the rest alone. All outputs on this page were produced on 11-29-2026 with Node.js 24 and Python 3.14.

Related reading: comment best practices explains what belongs in these comments, and the syntax reference covers the comment forms the grammar allows.

Table icon

Comparison of the Tools

Release dates come from each package registry. "Untouched" means that parsing the test file and printing it with no edit returned identical text.

ToolLanguageHow you editCurrent version (published)Untouched = identicalReads JSON5
@croct/json5-parserJavaScript, TypeScriptNode methods: set, delete, push, update, merge0.2.2 (12-01-2025)YesFull syntax, tested here
json5-trueformatTypeScriptRaw tree plus addKeyValue0.1.1 (04-29-2025)YesFull syntax, tested here
golden-fleeceJavaScriptpatch(text, newValue) compares and rewrites only what changed1.0.9 (06-05-2018)YesFull syntax, tested here
json5-writerJavaScriptwrite(newValue) through a recast tree0.2.0 (06-08-2020)Yes only with lineTerminator: '\n' on WindowsFull syntax, tested here; reformats edited nodes
jsonc-parserJavaScript, TypeScriptEdit list: modify then applyEdits3.3.1 (06-24-2024)Not applicable (edits only)No Corrupts files with single quotes or unquoted keys
json-fivePythonEdit a model, dump it with ModelDumper1.1.2 (06-11-2024)YesFull syntax, tested here
kotlin-json5Kotlin MultiplatformSource-aware edits: formatToEdits, applyJson5EditsSee its releases pageNot run for this pageDocumented as JSON5
Node.js logo

JavaScript and TypeScript Tools

@croct/json5-parser

Croct's package describes itself as a lossless tokenizer and parser that maintains indentation, spacing and comments. It is MIT licensed, has TypeScript types, and its only dependency is the small @croct/json package. Install it with npm install @croct/json5-parser. It is the best fit when you want a friendly, typed API.

const fs = require('node:fs'); const { JsonParser, JsonObjectNode, JsonArrayNode } = require('@croct/json5-parser'); const src = fs.readFileSync('app.json5', 'utf8'); const root = JsonParser.parse(src, JsonObjectNode); console.log(root.toString() === src); // true: nothing touched, nothing changed root.set('version', '1.3.0'); root.set('region', 'eu-west-1'); root.get('ports', JsonArrayNode).push(8082); root.get('features', JsonObjectNode).set('telemetry', true); fs.writeFileSync('app.json5', root.toString());

Real output of root.toString():

// Application settings { // semantic version, bumped by the release script version: '1.3.0', /* ports the dev server may use */ ports: [8080, 8081, 8082], // keep sorted features: { darkMode: true, // shipped in 1.1 beta: false, telemetry: true, }, name: 'demo-app', region: 'eu-west-1', }

Exactly four lines differ from the input, and the new array item and keys copied the file's existing style (single quotes, unquoted keys, trailing commas, one entry per line). The library learns style per block, so a file that mixes styles stays mixed. It kept CRLF line endings when we fed it a CRLF copy. Other useful calls are update(value), which reconciles a whole new object into the tree, merge(source), which merges two documents while keeping the comments of both, and toString(options) to restyle on purpose. A syntax error throws JsonParseError, for example Unexpected token '}' at 1:4. for the input {a:}; asking for the wrong root type throws JsonError.

json5-trueformat

A smaller TypeScript library, MIT licensed, that models the file as a document whose entries hold their own whitespace. It round-trips the test file exactly. The API is lower level: entries are JSON5ObjectEntry, array items are JSON5ArrayElement, and scalars are JSON5Literal nodes with a raw string and a quote character. JSON5Object.addKeyValue adds keys that match the surrounding layout; arrays you assemble yourself.

const t = require('json5-trueformat'); const doc = t.parseJSON5(fs.readFileSync('app.json5', 'utf8')); const root = doc.value; const entry = (k) => root.entries.find((e) => e instanceof t.JSON5ObjectEntry && e.key === k); entry('version').value.raw = '1.3.0'; const ports = entry('ports').value; const last = ports.elements.filter((e) => e instanceof t.JSON5ArrayElement).at(-1); last.comma = ','; // the old last item now needs a comma ports.elements.push(' ', new t.JSON5ArrayElement(new t.JSON5Literal('8082', ''), '', '')); root.addKeyValue('region', new t.JSON5Literal('eu-west-1', "'")); console.log(doc.toString());

The result keeps all comments and shows ports: [8080, 8081, 8082], // keep sorted. Two things to know from our run. If you push an array element without setting the previous comma and a space, you get the invalid text [8080, 80818082], because the tree is raw. And addKeyValue appended region: 'eu-west-1' without a trailing comma although the file used them, so a style-strict project should add the comma itself or run a formatter afterward.

golden-fleece

Rich Harris wrote golden-fleece for the Svelte REPL, which needed to update a user's data without reformatting it. Its approach is different: you evaluate the text into a normal object, change the object, and call patch(text, object), which compares the new object to the original syntax tree and rewrites only the nodes that differ. Version 1.0.9 dates from 2018, but it still ran correctly on current Node.js.

const fleece = require('golden-fleece'); const src = fs.readFileSync('app.json5', 'utf8'); const obj = fleece.evaluate(src); obj.version = '1.3.0'; obj.ports.push(8082); obj.region = 'eu-west-1'; obj.features.telemetry = true; console.log(fleece.patch(src, obj));

The output was identical to the croct output above, and patch(src, fleece.evaluate(src)) === src was true. This is the most natural workflow for scripts that already think in plain objects. The costs are that deleting a key can leave its comments attached to a neighbor (see the pitfalls), a value set to undefined throws Cannot stringify undefined, and a string containing an apostrophe is written escaped, as 'it\'s'.

json5-writer

An ISC-licensed package, version 0.2.0 from 2020, that parses the text into a JavaScript syntax tree and updates it through jscodeshift and recast. You call load(text), then write(object) with the full new value, then toSource().

const json5Writer = require('json5-writer'); const JSON5 = require('json5'); const writer = json5Writer.load(src); const data = JSON5.parse(src); data.version = '1.3.0'; data.ports.push(8082); data.region = 'eu-west-1'; data.features.telemetry = true; writer.write(data); console.log(writer.toSource({ lineTerminator: '\n' }));

Comments survived, but recast reprinted every node we changed and inserted blank lines. The "keep sorted" and "shipped in 1.1" trailing comments were moved onto their own lines above the entries, and the output looked like this:

// Application settings { // semantic version, bumped by the release script version: '1.3.0', /* ports the dev server may use */ // keep sorted ports: [8080, 8081, 8082], features: { // shipped in 1.1 darkMode: true, beta: false, telemetry: true, }, name: 'demo-app', region: 'eu-west-1', }

On Windows, the first run also changed every line ending to CRLF, apparently because recast follows the platform line ending by default; passing lineTerminator: '\n' made an untouched load identical. Its README notes that write removes any key missing from the value you pass, and that undefined keeps a value. Choose it only if reformatting an edited region is acceptable.

jsonc-parser (JSONC files only)

The MIT-licensed jsonc-parser (repository microsoft/node-jsonc-parser) never builds a document you print; modify(text, path, value, options) returns a list of edits (offset, length, replacement text) that applyEdits applies, so everything outside the edit range is untouched. That is a strong design, but the scanner only knows JSON with comments and trailing commas. In our run it did not understand single-quoted strings or unquoted keys, and modify did not throw when it met them.

const { modify, applyEdits } = require('jsonc-parser'); const opts = { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\n' } }; let out = jsoncText; out = applyEdits(out, modify(out, ['version'], '1.3.0', opts)); out = applyEdits(out, modify(out, ['ports', -1], 8082, { ...opts, isArrayInsertion: true })); out = applyEdits(out, modify(out, ['region'], 'eu-west-1', opts));

On a JSONC copy of the test file (double-quoted keys and strings) this worked, but two details matter. The edit reformatted the array it touched onto one value per line, and when darkMode was the last entry of its object, adding a key after it moved the trailing comment // shipped in 1.1 from the darkMode line to the new telemetry line. Run on the JSON5 test file itself, parse reported 19 errors and returned {}, and modify for version returned an edit that inserts a new double-quoted "version" key at the top of the object instead of changing the existing one. If the file can contain single quotes or unquoted keys, use one of the tools above. Compare the formats on JSON5 vs JSONC.

Python logo

Python: json-five

The PyPI package json-five (Apache license, Python 3.8 or newer) describes itself as a JSON5 parser that supports round-trip preservation of comments. Its README warns that the underlying model API and tokens are not stable and may break even in minor releases, so pin the version. One trap: you install json-five but import it as json5, the same name as the more common json5 package by a different author. Never install both in one environment; see the Python guide for how to tell the libraries apart.

Loading with ModelLoader gives a tree whose nodes carry wsc_before and wsc_after lists of whitespace strings and comment nodes. Dumping with ModelDumper printed our untouched test file identically. Editing the model needs care: replacing a node with a new one drops that node's whitespace, so we changed the existing string in place, and every new node gets its own whitespace list. Comments after a comma are stored in the next key's wsc_before, and the whitespace before a closing brace lives on the trailing comma node.

from json5.loader import loads, ModelLoader from json5.dumper import dumps, ModelDumper from json5 import model def key_name(k): return k.name if isinstance(k, model.Identifier) else k.characters def find(obj, name): return [key_name(k) for k in obj.keys].index(name) src = open('app.json5', newline='').read() doc = loads(src, loader=ModelLoader()) root = doc.value # bump a value in place so its surrounding whitespace survives version = root.values[find(root, 'version')] version.characters = '1.3.0' version.raw_value = "'1.3.0'" # append to an array: a new item needs its own leading space ports = root.values[find(root, 'ports')] new_port = model.Integer('8082') new_port.wsc_before = [' '] ports.values.append(new_port) # add a key to a nested object features = root.values[find(root, 'features')] key = model.Identifier('telemetry') key.wsc_before = ['\n '] value = model.BooleanLiteral(True) value.wsc_before = [' '] features.keys.append(key) features.values.append(value) # add a top-level key region_key = model.Identifier('region') region_key.wsc_before = ['\n '] region_val = model.SingleQuotedString('eu-west-1', "'eu-west-1'") region_val.wsc_before = [' '] root.keys.append(region_key) root.values.append(region_val) print(dumps(doc, dumper=ModelDumper()))

The printed text matched the croct output above, line for line, and loading it again with loads(out) returned the expected dictionary. Our first attempt skipped the whitespace lists and printed ports: [8080, 8081,8082] and beta: false,telemetry:true,: valid but ugly. Wrapping these steps in small helper functions is worth the effort in any project that edits files often. Run scripts like this with python -I if they sit next to untrusted files, so a stray json5.py beside them is not imported by mistake.

Kotlin logo

Kotlin: kotlin-json5

The Apache-licensed li.songe:json5 library by lisonge is a Kotlin Multiplatform parser whose README describes a lossless, source-aware document. Json5.parseToDocument recovers incomplete input and reports diagnostics, so it suits editor integrations. Its README says editor code can call Json5.formatToEdits and apply the result with source.applyJson5Edits(edits), which suggests an edit-list design like jsonc-parser's; we did not test whether unrelated comments and formatting stay untouched. quoteStrategy and unquotedKey control whether quotes are normalized when you re-encode.

Not run for this page. We could not build and run a Kotlin round trip here, so we show no sample and make no claim about its output. Read the README and tests, and write a round-trip test against your own file before relying on it. Other Kotlin and Java libraries listed in search results, such as json5-kotlin and json5k, document parsing and serialization, not editing in place.

For the Kotlin reader side, see the Kotlin guide.

Edit icon

Recipes

Each recipe uses @croct/json5-parser, the tool that gave the cleanest diff in our run. The same logic maps onto the other tools.

Bump a version

A release script that rewrites one field in place. It reads the file, checks the field exists so a typo does not silently add a new key, and writes back only when the text changed.

const fs = require('node:fs'); const { JsonParser, JsonObjectNode } = require('@croct/json5-parser'); function bumpVersion(file, next) { const src = fs.readFileSync(file, 'utf8'); const root = JsonParser.parse(src, JsonObjectNode); if (!root.has('version')) throw new Error(file + ' has no version key'); root.set('version', next); const out = root.toString(); if (out !== src) fs.writeFileSync(file, out); } bumpVersion('app.json5', '1.3.0');

Add a key

Use set on the object that should own the key. It adds the key if missing and replaces the value if present, copying the block's quote and comma style. Check the result with a real parse before saving, as shown in the pitfalls section.

root.set('region', 'eu-west-1'); // top level root.get('features', JsonObjectNode).set('telemetry', true); // nested

A key that is not a valid identifier, such as b-c, was written quoted ("b-c": 2) in our test, while a plain name like d stayed unquoted to match a file with unquoted keys.

Update an array

Get the array node, then use the usual array methods: push, unshift, splice, delete(index) and set(index, value). To replace the whole list with a new one, update reconciles it and keeps the comment that follows the array.

const ports = root.get('ports', JsonArrayNode); ports.push(8082); // ports: [8080, 8081, 8082], // keep sorted root.update({ ...root.toJSON(), ports: [9000] }); // ports: [9000], // keep sorted

When update got a whole new object, only the changed values and the new key were touched, and the comments stayed. It is slower than set for a single change, so reserve it for bulk updates.

Guard it with a test

Run the editor on a fixture in your test suite and assert two things: the untouched round trip is identical, and the edited file still parses to the data you expect.

const assert = require('node:assert'); const JSON5 = require('json5'); assert.strictEqual(JsonParser.parse(src, JsonObjectNode).toString(), src); const edited = JsonParser.parse(src, JsonObjectNode); edited.set('version', '1.3.0'); assert.strictEqual(JSON5.parse(edited.toString()).version, '1.3.0'); assert.ok(edited.toString().includes('// keep sorted'));
Warning icon

Pitfalls

  • Deleting a key orphans its comments. Comments are attached to neighbors, not to a key. Deleting ports with croct left // keep sorted alone on a line under the /* ports ... */ block comment. Deleting darkMode kept its trailing comment // shipped in 1.1 as a line inside features. With golden-fleece, deleting ports moved // keep sorted onto the version line. Delete the comment yourself, or review the diff.
  • Trailing comments can slide. In a JSONC object where darkMode was the last entry, adding a key after it made jsonc-parser move // shipped in 1.1 to the new line. Comments belong to positions, and editors guess.
  • Line endings. json5-writer converted LF to CRLF on Windows until we set lineTerminator. Check git diff --stat after the first run on each platform, and set * text eol=lf in .gitattributes if the team mixes systems.
  • The wrong parser can corrupt a file silently. jsonc-parser produced a broken edit rather than an exception on a JSON5 file. Never point a JSONC tool at single-quoted strings, unquoted keys or hex numbers.
  • Re-parse before you write. After any edit, parse the new text with JSON5.parse and compare it to the data you intended. A tree editor will happily print text that is not valid. That is exactly what raw array pushes in json5-trueformat and json-five can do.
  • Unstable or old APIs. json-five warns its model API can change in minor releases. golden-fleece and json5-writer have not published since 2018 and 2020, and json5-writer depends on jscodeshift 0.9. Pin versions and keep the round-trip test.
  • Do not hand-roll it with regular expressions. A pattern like /version: '(.*?)'/ breaks on a commented-out copy of the key, a differently quoted key, or a string containing the same text. Use a parser that understands the grammar described in the grammar reference.
  • Generated files are different. If a build step fully owns the file and nobody edits it by hand, plain stringify is fine and simpler. Preservation only matters for files people read and edit.
Checklist icon

Choosing a Tool

Your situationUseWhy
Node.js script, you want the least surprise@croct/json5-parserMost recent release of the JavaScript options, typed, learns the file's style, produced the smallest diff
You already work with plain objectsgolden-fleeceevaluate then patch needs almost no new API, but unmaintained since 2018
You need exact control over every tokenjson5-trueformatRaw tree; you handle commas and spaces yourself
Reformatting of edited regions is finejson5-writerSimple write call, but inserts blank lines and moves comments
The file is strict JSONC, like a tsconfig.jsonjsonc-parserEdit-list design that never rewrites untouched text; see the tsconfig guide
Pythonjson-five with ModelLoaderThe one Python option we ran that edits and keeps comments; pin the version
Kotlin or JVM editor toolingkotlin-json5Documented edit list; test it against your files first

If your tool must work for every file, consider whether you need to edit it at all. Putting values that scripts change (a version, a build number) in a small separate generated file, and leaving the commented file for humans, avoids the problem. The site's schema validation guide shows how to check an edited file against a schema afterward.

Question icon

Common Questions

Can JSON5.stringify keep comments?

No. The parser discards comments, so there is nothing left to write. The reference maintainers closed the request for it in 2020; use one of the libraries above.

Which tool should I use for package.json-style version bumps?

If the file is real JSON, JSON.parse and JSON.stringify are enough because JSON has no comments. For a commented JSON5 or JSONC file, @croct/json5-parser or jsonc-parser respectively, plus a test that the round trip is unchanged.

Why did my edit change a comment's position?

A comment is stored as whitespace next to a token, not as a property of a key. When the neighbor changes, the comment may stay with the old token. See the pitfalls section for the cases we hit.

Is there a Rust, Go or Java library that does this?

We did not verify one for this page, so we list none. The implementations list covers parsers in other languages, but parsing alone does not guarantee comment-preserving edits.

Does this work for JSON Lines or NDJSON?

Those formats have no comments at all. For their rules, see JSONL.rest, our sister reference site for JSON Lines and NDJSON.com, our sister reference site for NDJSON.

Sources

(10)
  1. croct-tech/json5-parser-js, README and source for @croct/json5-parser 0.2.2 (npm registry data read 11-29-2026)
  2. daniel-sc/json5-trueformat, README and package for 0.1.1
  3. Rich-Harris/golden-fleece, README and changelog for 1.0.9
  4. noahsug/json5-writer, README for 0.2.0
  5. microsoft/node-jsonc-parser, modify and applyEdits for 3.3.1
  6. spyoungtech/json-five and PyPI: json-five 1.1.2, README, model source and upload date
  7. JSONL.rest, our sister reference site for JSON Lines and NDJSON.com, our sister reference site for NDJSON, for the comment-free line formats mentioned in the questions
  8. lisonge/kotlin-json5, README sections on parseToDocument and source-aware edits (not run)
  9. json5/json5 issue #177, "Options for preserving comments when editing a JSON5 file by script"
  10. json5/json5 issue #122, "Generate JSON5"

Last reviewed: November 29, 2026.