Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Parser():
- def __init__(self, tokens):
- self.tokens = tokens
- self.i = 0
- self.t = None
- def peek(self):
- if self.end():
- return None
- self.t = self.tokens[self.i]
- return self.t
- def advance(self):
- self.i += 1
- return self.peek()
- def end(self):
- return self.i >= len(self.tokens)
- def parse(self):
- self.peek()
- if self.t['type'] == '{':
- result = self.parseObject()
- else:
- self.error('JSON Must start with brace `{`')
- return result
- def parseObject(self):
- self.advance()
- pairs = []
- first = True
- while not self.end():
- if self.t['type'] == '}':
- break
- if first:
- first = False
- elif self.t['type'] == ',':
- self.advance()
- if self.t['type'] == '}':
- break
- pairs.append(self.parsePair())
- self.advance()
- return pairs
- def parsePair(self):
- if self.t['type'] != 'str':
- self.error('Key must be type of string')
- key = self.t['val']
- val = ''
- tp = 'val'
- dataType = 'none'
- self.advance()
- if self.t['type'] != ':':
- self.error('Expected colon `:`')
- self.advance()
- if self.t['type'] in [ 'str', 'num', 'kw' ]:
- val = self.t['val']
- if self.t['type'] == 'str':
- dataType = 'string'
- elif self.t['type'] == 'kw' and self.t['val'] in [ 'false', 'true' ]:
- dataType = 'bool'
- elif self.t['type'] == 'num':
- dataType = 'double' if '.' in self.t['type'] else 'int'
- elif self.t['type'] == 'kw' and self.t['val'] == 'null':
- dataType = 'null'
- else:
- self.error('Unexpected type of token ' + self.t['type'])
- elif self.t['type'] == '{':
- val = self.parseObject()
- tp = 'obj'
- else:
- self.error('Unexpected type of token ' + self.t['type'])
- self.advance()
- return {
- "key": key,
- "val": val,
- "type": tp,
- "dataType": dataType
- }
- def error(self, message):
- raise Exception('[PARSER][ERROR] ' + message)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement