Skip to content

Instantly share code, notes, and snippets.

@metaory
Last active August 11, 2024 16:29
Show Gist options
  • Save metaory/70f15c242ca5c423638b6fcea843171d to your computer and use it in GitHub Desktop.
Save metaory/70f15c242ca5c423638b6fcea843171d to your computer and use it in GitHub Desktop.
Basic JSONC SED Parser

Basic JSONC Parser

Note

it removes

  • Comments to end of line
  • Single line block comments
  • Empty lines

Caution

its NOT covering

  • Full spec
  • Trailing Commas
  • comments in values
  • Multi line block comments

TL;DR

s/\/\/.*$//g;s/\/\*.*\*\///g;/^[[:space:]]*$/d

basic-jsonc.sed

:comments-to-endofline
s/\/\/.*$//g

:comment-blocks
s/\/\*.*\*\///g

:empty-lines
/^[[:space:]]*$/d
sed -f basic-jsonc.sed test-file.jsonc

# pipe to jq
sed -f basic-jsonc.sed test-file.jsonc | jq '.'

# replace in place
sed -i -f basic-jsonc.sed test-file.jsonc

Example JSONC

//test-file.jsonc
{
  // hoge
  "foo": "bar", // here
  "no": "comment in values are NOT ok",
  "@umm": "guys is /* block */ fine too?",
  /* are you fine? */
  "hmm": /* even here? */ "comment block in values not ok",
  "test": "yup some good",
  "comment at end of value?": "nope",
  "indent": "hey covered tab and nested?",
  "ind": {
    "hoge": /* just saying */ [
			"x11", /* behind me are tabs! */
      "yup u okk",


      "mixed multiline empty lines above",
      "HOUSTON WE HAVE A PROBLEM",
      "watt?",
      "TRAILING COMMAS",
      "i knw, i'm too lazy, deal with it!",
      "i can avoid them, or write more regex",
      "comments are enough for nw"
    ], // okkk
    "res": "ok"
  }
  // zxzzz
}
inline pattern

sed 's/\/\/.*$//g;s/\/\*.*\*\///g;/^[[:space:]]*$/d' test-file.jsonc | jq

:comments-to-endofline
s/\/\/.*$//g
:comment-blocks
s/\/\*.*\*\///g
:empty-lines
/^[[:space:]]*$/d
//test-file.jsonc
{
// hoge
"foo": "bar", // here
"no": "comment in values are NOT ok",
"@umm": "guys is /* block */ fine too?",
/* are you fine? */
"hmm": /* even here? */ "comment block in values not ok",
"test": "yup some good",
"comment at end of value?": "nope",
"indent": "hey covered tab and nested?",
"ind": {
"hoge": /* just saying */ [
"x11", /* behind me are tabs! */
"yup u okk",
"mixed multiline empty lines above",
"HOUSTON WE HAVE A PROBLEM",
"watt?",
"TRAILING COMMAS",
"i knw, i'm too lazy, deal with it!",
"i can avoid them, or write more regex",
"comments are enough for nw"
], // okkk
"res": "ok"
}
// zxzzz
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment