I need to parse a simple JSON string (flat JSON, no hierarchy) for keys and values, and there is a system constraint that I cannot use any built-in JSON library and can only read a string once due to latency requirements. I need to use Python 2.7.x series and cannot use a higher version.
Note: This question is version 3 of my code to solve this problem.
Version 1 - answered by @holroy
Version 2 - answered by @Tersosauros
This is a new version of code based on guidance from @Tersosauros' post of the previous version. Note that I still do not handle some corner cases. I do not want to use two state variables as with @Tersosauros' code, but rewrote using only one state variable. I am not 100% confident if my code is correct logic and your advice is highly appreciated.
READY = 0
COLON = 1
COMMA = 2
STRING = 3
NUMBER = 4
numbers='0123456789.'
NoOps=' {'
def parse(strJSON):
state = READY
lastKey=''
lastValue=''
temp=''
result={}
for c in strJSON:
if state == READY:
if c in NoOps:
continue
elif c == '"':
state = STRING
elif c == ':':
lastKey=temp
temp=''
state = READY
elif c == ',' or c=='}':
lastValue=temp
temp=''
if lastKey:
result[lastKey]=lastValue
lastValue=''
lastKey=''
state=READY
elif c in numbers:
state=NUMBER
elif state == STRING:
if c == '"':
state = READY
else:
temp += c
if state == NUMBER:
if c in NoOps or c==',' or c=='}':
lastValue=temp
temp=''
if lastKey:
result[lastKey]=lastValue
lastValue=''
lastKey=''
state=READY
else:
temp+=c
if lastKey:
result[lastKey]=lastValue
return result
if __name__ == "__main__":
#JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"]}'
JSONString1 = '{ "id": "1", "name": "A green door", "price": "12.50", "tags": "home green"}'
JSONString2 = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": "home green"}'
print parse(JSONString1)
print parse(JSONString2)
temp
, as this conveys nothing about what that variable represents. \$\endgroup\$state
variable. \$\endgroup\$