Skip to content

Instantly share code, notes, and snippets.

@jrusev jrusev/parse.py
Last active Feb 17, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.