If I don't have the option of using any external module, my typical approach is to first just sanitize the input (i.e. remove the trailing commas and comments) and then use the built-in JSON parser.
Here's an example that uses three regular expressions to strip both single-line and multi-line comments and then trailing commas on the JSON input string then passes it to the built-in json.loads
method.
#!/usr/bin/env python
import json, re, sys
unfiltered_json_string = '''
{
"name": "Grayson",
"age": 45,
"car": "A3",
"flag": false,
"default": true,
"entries": [ // "This is the beginning of the comment with some quotes" """""
"red", // This is another comment. " "" """ """"
null, /* This is a multi line comment //
"Here's a quote on another line."
*/
false,
true,
],
"object": {
"key3": null,
"key2": "This is a string with some comment characters // /* */ // /////.",
"key1": false,
},
}
'''
RE_SINGLE_LINE_COMMENT = re.compile(r'("(?:(?=(\\?))\2.)*?")|(?:\/{2,}.*)')
RE_MULTI_LINE_COMMENT = re.compile(r'("(?:(?=(\\?))\2.)*?")|(?:\/\*(?:(?!\*\/).)+\*\/)', flags=re.M|re.DOTALL)
RE_TRAILING_COMMA = re.compile(r',(?=\s*?[\}\]])')
if sys.version_info < (3, 5):
# For Python versions before 3.5, use the patched copy of re.sub.
# Based on https://gist.github.com/gromgull/3922244
def patched_re_sub(pattern, repl, string, count=0, flags=0):
def _repl(m):
class _match():
def __init__(self, m):
self.m=m
self.string=m.string
def group(self, n):
return m.group(n) or ''
return re._expand(pattern, _match(m), repl)
return re.sub(pattern, _repl, string, count=0, flags=0)
filtered_json_string = patched_re_sub(RE_SINGLE_LINE_COMMENT, r'\1', unfiltered_json_string)
filtered_json_string = patched_re_sub(RE_MULTI_LINE_COMMENT, r'\1', filtered_json_string)
else:
filtered_json_string = RE_SINGLE_LINE_COMMENT.sub(r'\1', unfiltered_json_string)
filtered_json_string = RE_MULTI_LINE_COMMENT.sub(r'\1', filtered_json_string)
filtered_json_string = RE_TRAILING_COMMA.sub('', filtered_json_string)
json_data = json.loads(filtered_json_string)
print(json.dumps(json_data, indent=4, sort_keys=True))
ast.literal_eval
.{number: .75, number2: .1E2}
would be invalid. It employs#
and//
for comments, but provides no/* block comment method */
. Other than that, it's awesome.