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. It looks a bit ugly and I'm looking for advice in this problem, for both efficiency and reliability.
def findKeyValue(str1, lastndex):
keyIndexBegin=str1.rfind(":",0,lastndex)
keyIndexBegin=str1.rfind("\"",0,keyIndexBegin)
keyIndexBegin=str1.rfind("\"",0,keyIndexBegin)
keyIndexBegin+=1
keyIndexEnd=str1.find("\"",keyIndexBegin)
print "Key is: " + str1[keyIndexBegin:keyIndexEnd]
valueBeginIndex=str1.find(":",keyIndexEnd+1)
valueEndIndex=index
print "Value is: "+ str1[valueBeginIndex:valueEndIndex]
if __name__ == "__main__":
#JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"]}'
JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": "home green"}'
index = JSONString.find(",")
while index != -1:
findKeyValue(JSONString, index)
index = JSONString.find(",",index+1)
# handle the last one
index=len(JSONString)-1
findKeyValue(JSONString,index)