Page 1 of 1

unable to parse json client side...

Posted: Mon Jul 26, 2010 10:35 pm
by aayushraj
Hi,
I have created a nested JSON object using the following php code :

Code: Select all

while($row = $result->fetch_assoc())
		{
			$fname = $row['uname'];
			$name = getName($fname);
			
			$temp = array(name=>$name, fname=>$fname);
			$ret_val[] = json_encode($temp);
		}
		
		return json_encode($ret_val);
Now I am processing this json in Javascript(using jQuery) as follows:

Code: Select all

function(data)  // data contains the JSON object
{	
       alert(data);
	//alert(data.result);
	//alert(result.length);
	for(var i=0;i<data.length;i++)
	{
		var obj = data[i];
		alert(obj);
		for(var key in obj)
	        {
			alert(key);
		}	
	}
}
alert(data) gives th following output : {"name":"Apurv Prakash","uname":"aprakash"},{"name":"xyz","uname":"abc"},{"name":"XYZ1","uname":"ABC1"} while I think it should give the following output :
[ {"name":"Apurv Prakash","uname":"aprakash"},{"name":"xyz","uname":"abc"},{"name":"XYZ1","uname":"ABC1"}] // Extra square brackets at the beginning and end.
If this is so then what should I change in the PHP code.

alert(obj) is giving output : {"name":"Apurv Prakash","uname":"aprakash"} then {"name":"xyz","uname":"abc"} and so on....

but alert(key) is giving the following output : 0 1 2 3..... instead of the expected name and uname....

I am not sure if the error is in PHP code or the JS code...

I have been stuck on this since past two days.. Please help...

Re: unable to parse json client side...

Posted: Tue Jul 27, 2010 5:01 am
by VladSun
How about:

Code: Select all

while($row = $result->fetch_assoc())
{
		$ret_val[] = array
		(
			name	=> getName($fname), 
			fname	=> $row['uname']
		);
}
                
return json_encode($ret_val);