json-parser
JSON parser to parse JSON object and MAINTAIN comments.
This is a very low level module. For most situations, recommend to use comment-json
instead.
What's new in 2.x
json-parser@2.x
brings some breaking changes by completely refactoring with Symbol
s
- supports comments everywhere, yes, EVERYWHERE in a JSON file, eventually 😆
- fixes the known issue about comments inside arrays.
Install
$ npm i json-parser
Usage
const {parse} = require('json-parser')
parse(text, reviver? = null, remove_comments? = false)
: object | string | number | boolean | null
- text
string
The string to parse as JSON. See the JSON object for a description of JSON syntax. - reviver?
Function() | null
Default to null
. It acts the same as the second parameter of JSON.parse
. If a function, prescribes how the value originally produced by parsing is transformed, before being returned. - remove_comments?
boolean = false
If true, the parsed JSON Object won't contain comments
Returns object | string | number | boolean | null
corresponding to the given JSON text.
content
{
"foo" :
1
,
"bar": [
"baz"
,
"quux"
]
}
console.log(parse(content))
And the result will be:
{
[Symbol.for('before-all')]: [{
type: 'BlockComment',
value: '\n before-all\n ',
inline: false
}, {
type: 'LineComment',
value: ' before-all',
inline: false
}],
...
[Symbol.for('after-prop:foo')]: [{
type: 'BlockComment',
value: ' after-prop:foo ',
inline: true
}],
foo: 1,
bar: [
"baz",
"quux,
// The property of the array
[Symbol.for('after-value:0')]: [{
type: 'LineComment',
value: ' after-value:0',
inline: true
}, ...],
...
]
}
There are SEVEN kinds of symbol properties:
Symbol.for('before-all')
Symbol.for('before')
Symbol.for(`after-prop:${prop}`)
Symbol.for(`after-colon:${prop}`)
Symbol.for(`after-value:${prop}`)
Symbol.for(`after-comma:${prop}`)
Symbol.for('after-all')
And the value of each symbol property is an array of CommentToken
interface CommentToken {
type: 'BlockComment' | 'LineComment'
value: string
inline: boolean
}
console.log(parse(content, null, true))
And the result will be:
{
foo: 1,
bar: [
"baz",
"quux"
]
}
Special cases
const parsed = parse(`
// comment
1
`)
console.log(parsed === 1)
If we parse a JSON of primative type with remove_comments:false
, then the return value of parse()
will be of object type.
The value of parsed
is equivalent to:
const parsed = new Number(1)
parsed[Symbol.for('before-all')] = [{
type: 'LineComment',
value: ' comment',
inline: false
}]
Which is similar for:
For example
const parsed = parse(`
"foo" /* comment */
`)
Which is equivalent to
const parsed = new String('foo')
parsed[Symbol.for('after-all')] = [{
type: 'BlockComment',
value: ' comment ',
inline: true
}]
But there is one exception:
const parsed = parse(`
// comment
null
`)
console.log(parsed === null)
License
MIT