I have a string returned from python by json.dumps(). I am using python 2.6 or 2.7. When I parse it using JSON.parse() in JavaScript. I got undefined with keys.
My string recieved by javascript(ajax) is looks like:
{'country': u'\u4e0a', 'Search': {'city_num': 25, 'index': ''}, 'Locc': ['116.116', '29.29'], 'cid': '285'} When I use:
objstr = JSON.parse(jsonstr); alert(objstr.country); I got undefined in popup alert window.objstr[0].country and objstr[0]['country'] got undefined either.
What should I do? I have read several article on stackoverflow and google and I still confused about how to solve this problem. Any one can give me some advices? Thanks.
Edit
My codes to receive request from ajax:
def POST(self): resultline = {} file = open("..\\cache\\res.cache", 'r') last_pos = self.get_pos() print last_pos pos = int(last_pos) file.seek(pos) line = file.readline() print line if ''== line: file.seek(0, 0) line = file.readline() last_pos = file.tell() self.store_pos(last_pos) resultline = line file.close() if '' != resultline: resultlinetmp = resultline[0:len(resultline)-1] return json.dumps(resultlinetmp)
u'\u4e0a'is causing the issue, there is auoutside the single quotesjson.dumps()? That looks like thereprof the dictionary.objstr.cidgotundefinedeither. @rps'country': u'\u4e0a'is causing the issue, json values ar not supposed to have anything outside", but by default python strings are used as unicode, so you should not usejson.dumps(), better use a custom encoder to output normal string instead of unicode strings.