Created
March 18, 2019 06:55
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source = """ | |
{ | |
"root1" | |
{ | |
"item1" "1" | |
"item2" "abc" | |
"item3" | |
{ | |
"cell" | |
{ | |
"cell1" | |
{ | |
"cell1Name" "99" | |
} | |
"cell2" | |
{ | |
"cell2Name" "cdb" | |
} | |
} | |
} | |
"item4" "valueI" | |
} | |
"root2" | |
{ | |
"item1" "88" | |
"item2" "tg" | |
"item3" | |
{ | |
"cell" | |
{ | |
"cell1" | |
{ | |
"cell1Name" "99" | |
} | |
"cell2" | |
{ | |
"cell2Name" "ujh" | |
} | |
} | |
} | |
"item4" "valueb" | |
} | |
} | |
""" | |
i = 0 | |
LP=1 | |
RP=2 | |
def nextToken(): | |
global i | |
while i < len(source) and source[i].isspace(): | |
i += 1 | |
if source[i] == '{': | |
i += 1 | |
return LP | |
if source[i] == '}': | |
i += 1 | |
return RP | |
if source[i] == '"': | |
start = i | |
i += 1 | |
while i < len(source) and source[i] != '"': | |
i += 1 | |
if i < len(source): | |
i += 1 | |
return source[start+1:i-1] | |
else: | |
raise Exception('expect "') | |
raise Exception('expect {}"') | |
def parseValue(): | |
nt = nextToken() | |
if nt == LP: | |
return parseObject() | |
if nt == RP: | |
raise Exception('expect { or string') | |
return nt | |
def parseObject(): | |
obj = {} | |
while True: | |
nt = nextToken() | |
if nt == RP: | |
return obj | |
if nt == LP: | |
raise Exception('expect string') | |
k = nt | |
v = parseValue() | |
obj[k] = v | |
return obj | |
print(parseValue()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment