Skip to content

Instantly share code, notes, and snippets.

@RPGillespie6
Created August 16, 2022 21:30
Show Gist options
  • Save RPGillespie6/57326cad687380328e8a657c17148540 to your computer and use it in GitHub Desktop.
Save RPGillespie6/57326cad687380328e8a657c17148540 to your computer and use it in GitHub Desktop.
Convert JSONC to JSON from stdin or file
#!/usr/bin/env python3
# Convert a JSONC (JSON with Comments) file to vanilla JSON from CLI
#
# Sample usage:
# cat sample.jsonc | ./scripts/jsonc_to_json.py | jq
# python3 jsonc_to_json.py sample.jsonc
import re
import sys
# https://stackoverflow.com/a/23705538
def removeTrailingJsonCommas(jsonText):
jsonText = re.sub(",[ \t\r\n]+}", "}", jsonText)
jsonText = re.sub(",[ \t\r\n]+\]", "]", jsonText)
return jsonText
# https://stackoverflow.com/a/241506
def removeComments(text):
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return " " # note: a space and not an empty string
else:
return s
pattern = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE)
return re.sub(pattern, replacer, text)
def main():
# Read from either file specified from CLI arg or stdin
if len(sys.argv) > 1:
with open(sys.argv[1]) as f:
fileStr = f.read()
else:
fileStr = sys.stdin.read()
fileStr = removeTrailingJsonCommas(fileStr)
fileStr = removeComments(fileStr)
print(fileStr)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment