Skip to content

Instantly share code, notes, and snippets.

@jrusev
Last active February 17, 2017 21:09
Show Gist options
  • Save jrusev/6f0835105600b8c537d8437b542c7479 to your computer and use it in GitHub Desktop.
Save jrusev/6f0835105600b8c537d8437b542c7479 to your computer and use it in GitHub Desktop.
def parse(s):
"""Parse a JSON string containing only integers and arrays."""
return int(s) if s[0].isdigit() else parse_array(s, 1)[0]
def parse_array(s, i):
"""Return the array beginning at index i and the end index of the array."""
res = []
while s[i] != ']':
if s[i].isdigit():
start = i
while s[i].isdigit(): i+= 1
res.append(int(s[start:i]))
elif s[i] == '[':
arr, i = parse_array(s, i+1)
res.append(arr)
else: i += 1
return res, i+1
if __name__ == '__main__':
tests = [
1,
[],
[1],
[[]],
[123],
[1,2],
[[1]],
[[1,2]],
[[],[]],
[[[[]]]],
[1,2,[]],
[1,2,[3]],
[[1,2],3],
[1,[2],3],
[1,[2,3],4],
[1,2,[3,4]],
[1,2,[3,4],5],
[1,2,[3,4,[5]]],
]
for t in tests:
assert parse(str(t)) == t
print 'OK'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment