1

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) 
13
  • u'\u4e0a' is causing the issue, there is a u outside the single quotes Commented May 19, 2014 at 5:59
  • 2
    Are you sure you are using json.dumps()? That looks like the repr of the dictionary. Commented May 19, 2014 at 6:00
  • It is returned by 'return str(json.dumps(resultline))'. @Tim Commented May 19, 2014 at 6:02
  • Well how to convert the unicode string? objstr.cid got undefined either. @rps Commented May 19, 2014 at 6:02
  • '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 use json.dumps(), better use a custom encoder to output normal string instead of unicode strings. Commented May 19, 2014 at 6:07

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.