The jsonc string from which comments need to be removed.
A string representing the jsonc-equivalent content, without comments and trailing commas.
import { assertEquals } from "jsr:@std/assert"
const my_jsonc = `
{
// inline comment
"key1": "value1",
/* block comment */ "key2": 2,
/* multiline block comment
* hello
* world
*/
"key3": {
"//key4": "value4 //",
"jsonInComment": "/* { \\"key\\": \\"value\\" } */",
"trickyEscapes": "a string with \\\\\\"escaped quotes\\\\\\" and /* fake comment */ inside and \\newline",
},
"array1": [
"/* not a comment */",
"// also not a comment",
"has a trailing comma" // trailing comma below \t \t tab characters.
, // <-- trailing comma here. and some more \t \t tab characters.
],
/* Block comment containing JSON:
{ "fakeKey": "fakeValue" },
*/
"arr//ay2": [
true, false, { "1": false, "2": true, },
42,7,
// scientific notation
1e10,],
}`
const expected_value = {
key1: "value1",
key2: 2,
key3: {
"//key4": "value4 //",
jsonInComment: `/* { "key": "value" } */`,
trickyEscapes: `a string with \\"escaped quotes\\" and /* fake comment */ inside and \newline`,
},
array1: [
"/* not a comment */",
"// also not a comment",
"has a trailing comma",
],
"arr//ay2": [ true, false, { "1": false, "2": true }, 42, 7, 10000000000, ]
}
const
my_json = jsoncRemoveComments(my_jsonc),
my_parsed_json = JSON.parse(my_json)
assertEquals(my_parsed_json, expected_value)
remove comments and trailing commas from a "jsonc" (json with comments) string.
in a jsonc-string, there three additional features that supersede a regular json-string:
//
(that is not part of a string) is a comment, until the end of the line./* ... */
) is a comment.,
) after the last element of an array, or the last entry of a dictionary.moreover, this function also trims unnecessary whitespaces and newlines outside of string literals.
once you have converted your jsonc-string to a json-string, you will probably want to use
JSON.parse
to parse the output.