Parsing this json data

Discussion in 'JavaScript' started by ranacseruet, Dec 28, 2009.

  1. #1
    I am getting json data from a web service like as follows:

    {"d":["Escaldes AD","Abu Dhabi - Airport Road AE"]}

    but data.d is showing as undefined. How can I parse this data using javascript/jquery efficiently?

    Regards
     
    ranacseruet, Dec 28, 2009 IP
  2. ranacseruet

    ranacseruet Peon

    Messages:
    302
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I got the solution, because its returning data as string, not json object, so what we have to do...
    eval("var data = "+data);

    now it will get the json data :D, great, may be it will be helpfull to somebody else in future...
     
    ranacseruet, Dec 29, 2009 IP
  3. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #3
    well duh. doing this eval is a bit risky if your source is 3-rd party, you should not trust the data to eval it! unless--you don't mind XSS vulnerabilities...

    here is how this is being done in mootools in a 'safer' way - the JSON hash's .decode method can give you some ideas:
    
    	decode: function(string, secure){
    		if ($type(string) != 'string' || !string.length) return null;
    		if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
    		return eval('(' + string + ')');
    	}
    
    Code (javascript):
     
    dimitar christoff, Dec 30, 2009 IP
  4. ranacseruet

    ranacseruet Peon

    Messages:
    302
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks for your suggestion. I will use this from now on :)
     
    ranacseruet, Dec 30, 2009 IP