json5-writer
Comment-preserving JSON / JSON5 parser
json5-writer provides an API for parsing JSON and JSON5 without losing comments or formatting. It does so by transforming JSON5 into a JavaScript AST and using jscodeshift to update values.
Example
const json5Writer = const config = fsconst writer = json5Writerwriterfs
config.json5
diff
{ // actions 'eat honey': {- cooldown: 4,+ cooldown: 3, },+ + 'speak': {+ cooldown: 2,+ }, // Note: A day without a friend is like a pot without a single drop of honey left inside. // entities 'bear': {- actions: [ 'eat honey' ],- canSpeak: true,+ actions: ['eat honey', 'speak'], }, }
Installation
npm install --save json5-writer
Usage
const writerInstance = json5Writer // get a writer instance for the given JSON / JSON5 stringwriterInstance // update jsonStr, preserving commentsconst ast = writerInstanceast // directly access the AST with jscodeshift APIconst newJson5 = writerInstance // get the modified JSON5 stringconst newJson = writerInstance // get the modified JSON string
.write(value)
Updates the JSON / JSON5 string with the new value. Any field or property that doesn't exist in value
is removed.
To keep an existing value, use undefined
:
const writer = json5Writerwriterwrite // [{ name: 'Noah', age: 28 }, { name: 'Nancy' }]
.ast
Directly access the JSON5-turned-JavaScript AST, wrapped in the jscodeshift API.
const j = const writer = json5Writerwriterastwrite // [1, 0, 3, 0]
.toSource(options)
Get the modified JSON5 string. Alias for .toJSON5()
.
options
control what is output. By default, single quotes and trailing commas are enabled and key quote usage is inferred.
quoteKeys
controls whether object keys are quoted. It can have three different values:false
- no object keys will have quotestrue
- all object keys will have quotesundefined
- object key quote usage is inferred [default]
quote
can be eithersingle
ordouble
View the remaining options here.
.toJSON(options)
Same as .toSource(options)
but with quote: 'double'
, trailingComma: false
, quoteKeys: true
by default.