Created
August 25, 2011 09:16
-
-
Save WizKid/1170297 to your computer and use it in GitHub Desktop.
Remove comments in a JSON file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def removecomments(s): | |
inCommentSingle = False | |
inCommentMulti = False | |
inString = False | |
t = [] | |
l = len(s) | |
i = 0 | |
fromIndex = 0 | |
while i < l: | |
c = s[i] | |
if not inCommentMulti and not inCommentSingle: | |
if c == '"': | |
slashes = 0 | |
for j in xrange(i - 1, 0, -1): | |
if s[j] != '\\': | |
break | |
slashes += 1 | |
if slashes % 2 == 0: | |
inString = not inString | |
elif not inString: | |
if c == '#': | |
inCommentSingle = True | |
t.append(s[fromIndex:i]) | |
elif c == '/' and i + 1 < l: | |
cn = s[i + 1] | |
if cn == '/': | |
inCommentSingle = True | |
t.append(s[fromIndex:i]) | |
i += 1 | |
elif cn == '*': | |
inCommentMulti = True | |
t.append(s[fromIndex:i]) | |
i += 1 | |
elif inCommentSingle and (c == '\n' or c == '\r'): | |
inCommentSingle = False | |
fromIndex = i | |
elif inCommentMulti and c == '*' and i + 1 < l and s[i + 1] == '/': | |
inCommentMulti = False | |
i += 1 | |
fromIndex = i + 1 | |
i += 1 | |
if not inCommentSingle and not inCommentMulti: | |
t.append(s[fromIndex:len(s)]) | |
return "".join(t) |
I have run it though tests from https://github.com/getify/JSON.minify/blob/master/minify_json.py and it doesn't pass...
that's what happens when you write code in your browser!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Free to use/copy/modify/redistribute?