Apply object changes to a JSON / JSONC string while preserving formatting, comments, and original whitespace style.
jsoncPatch diffs your source text against a target object and replays the changes in place, so comments, trailing commas, indentation, and spacing all survive the edit.
- The source text is parsed with
jsonc-parser. - The diff between the parsed source and the target object is computed with
fast-json-patch(RFC 6902). - Each patch operation is replayed through
jsonc-parser'smodify(), so the output keeps all original formatting.
Removals are applied before adds/replaces and paths are sorted in reverse order to avoid index-shifting bugs when patching arrays.
npm install jsonc-patchpnpm add jsonc-patchimport { jsoncPatch } from 'jsonc-patch'
// or: import jsoncPatch from 'jsonc-patch'
jsoncPatch('{ "a": 1 }', { a: 1, b: 2 })
// => '{ "a": 1, "b": 2 }'jsoncPatch('{ "a": 1 }', { a: 1, b: 2 })
// => '{ "a": 1, "b": 2 }'jsoncPatch('{ "a": 1, "b": 2 }', { a: 1, b: 3 })
// => '{ "a": 1, "b": 3 }'jsoncPatch('{ "a": 1, "b": 2 }', { a: 1 })
// => '{ "a": 1 }'jsoncPatch('{ /* hello */ "a": 1 }', { a: 2 })
// => '{ /* hello */ "a": 2 }'jsoncPatch('{ "a": 1, }', { a: 2 })
// => '{ "a": 2, }'jsoncPatch('{ "arr": [1, 2, 3] }', { arr: [1, 4, 3] })
// => '{ "arr": [1, 4, 3] }'jsoncPatch('{ "a": { "x": 1 } }', { a: { x: 2 } })
// => '{ "a": { "x": 2 } }'jsoncPatch('', { foo: 'bar' })
// => '{ "foo": "bar" }'jsoncPatch('{"a":1}', { a: 2 }, { formattingOptions: { insertSpaces: true, tabSize: 2 } })
// => '{\n "a": 2\n}'function jsoncPatch<T extends object>(
text: string,
object: T,
options?: ModificationOptions
): stringtext— Original JSON / JSONC text. If empty or falsy, defaults to"{}".object— Target plain object whose properties become the result.options— OptionalModificationOptionsforwarded tojsonc-parser'smodify().
Returns the updated JSONC string.
MIT