Skip to content

Instantly share code, notes, and snippets.

@alex-lx
Created March 18, 2019 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-lx/199038ac21c974e8e621742a45cbfe4f to your computer and use it in GitHub Desktop.
Save alex-lx/199038ac21c974e8e621742a45cbfe4f to your computer and use it in GitHub Desktop.
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