Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Remove comments in a JSON file

View gist:1170297
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
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)

Free to use/copy/modify/redistribute?

I have run it though tests from https://github.com/getify/JSON.minify/blob/master/minify_json.py and it doesn't pass...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.