Skip to content

Instantly share code, notes, and snippets.

@ssadler
Created March 2, 2013 12:19
Show Gist options
  • Save ssadler/5070757 to your computer and use it in GitHub Desktop.
Save ssadler/5070757 to your computer and use it in GitHub Desktop.
json parser
def parse(data):
char = data.pop(0)
if char == '[':
return parse_list(data)
elif char == '{':
return parse_object(data)
elif '0' <= char <= '9':
return parse_int(char, data)
elif char in 'tfn':
return parse_atom(data)
elif char == '"':
return parse_string(data)
else:
lol_parser_error()
def parse_atom(data):
part = data.pop(0) + data.pop(0) + data.pop(0)
if part == 'ull':
return None
if part == 'rue':
return True
if part == 'als':
data.pop(0)
return False
parser_error()
def parse_list(data):
out = []
while True:
out.append(parse(data))
char = data.pop(0)
if char == ']':
return out
else:
assert char == ','
def parse_object(data):
out = {}
while True:
key = parse(data)
assert data.pop(0) == ':'
out[key] = parse(data)
char = data.pop(0)
if char == '}':
return out
else:
assert char == ','
def parse_string(data):
out = []
while True:
char = data.pop(0)
if char == '"':
return ''.join(out)
elif char == '\\':
out.append(data.pop(0))
else:
out.append(char)
def parse_int(value, data):
while '0' <= data[0] <= '9':
value += data.pop(0)
return int(value)
json = '[1,null,2,[1,2,{"gg\\"":2,3:400,true:false}]]'
print parse(list(json))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment