Friday 19 October 2012

How to parse json data with jquery

Json
JSON stands for JavaScript Object Notation. JSON is lightweight text-data interchange format. now here we are going to parse json response in javascript using jquery ajax.

ajax.php
Here in this file we will write json_encode function to convert php array in json string.


<?php
//** Types of json format
 

//** 1)
$obj['firstname'] = "John";
$obj['lastname'] = "Smith";
$obj['email'] = "john.smith@johnsmith.com";
$response = json_encode($obj);
//** o/p  {“firstname”:"John",”lastname”:”Smith","email":"john.smith@johnsmith.com"}

//** above is a single Literal or one dimensional array format


//** 2) another way
$obj=array('0'=>array('firstname' => "John",'email'=> "john@johnsmith.com", 'address'=>array('city'=>'bangalore','state'=>'karnataka')),
'1'=>array('firstname' => "Smith",'email'=> "smith@johnsmith.com", 'address'=>array('city'=>'delhi','state'=>'delhi'))
);

$response = json_encode($obj);


//** json_encode() Returns the JSON representation of a value


/* o/p -
 [{"firstname":"John","email":"john@johnsmith.com","address":{"city":"bangalore","state":"karnataka"}},{"firstname":"Smith","email":"smith@johnsmith.com","address":{"city":"delhi","state":"delhi"}}]

*/
//** above is multi dimensional array and will reside inside [ ] square brackets
//** Json format must be in “ “ double quote only, both keys and values , “City”:”Bangalore”


print $response ;  //** this $response  will be fetched by calling Ajax function at json.php page

exit();
?>


json.php:

Here we will write Ajax query to fetch json response from ajax.php file. we are using jquery ajax

<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

$.ajax({
url: "axon_test.php",
data: { get_param: 'value' },
cache: false,
dataType: "json",   
    success: function (responseText) {      
  var json = responseText;
   $(json).each(function(i,val){
$.each(val,function(k,v){
          console.log(k+" : "+ v);  //** o/p firstname : John
if(k=="address"){
var obj=v;
console.log(obj.city); //**  o/p Bangalore
}
});
  });

    } //** success ends
}); //** Ajax end

});  //** document ends

 

Important as we are using dataType “json” in Ajax call, so jquery will convert the Json response (json formatted string) into javascript object automatically, we don’t need to use parseJSON(); function.
for single dimensional response responseText = “ [Object] “.
for multi dimensional response responseText  =” [object object]”.
then loop through  responseText and  access individual values.

by using jquery ajax function we don’t need to use eval() also, and work on all browser



//*** without using ajax , we can parse json notation using parseJSON() function

$(document).ready(function() {

var temp='[{"firstname":"sam","ID":"1"},{"firstname":"jQuery","ID":"2"}]';
var temp1=$.parseJSON(temp);
console.log(temp1);
//** o/p  [Object { firstname="sam",  ID="1"}, Object { firstname="jQuery",  ID="2"}]
console.log(temp1.firstname);
//** o/p jquery   “  sam “
});

</script>