JSON(JavaScript Object Notation)


JSON, or Javascript Object Notation, is a simple, lightweight way to transmit data to transmit data from PHP to Javascript, and vice-versa. In Javascript, it is a very powerful tool to parse and evaluate strings and make them objects. It is also used as an alternative to XML in AJAX, becoming instead AJAJ(Asynchronous Javascript and JSON). It is faster than XML, since it is much simpler and already native to Javascript.

  • json_encode

    • json_encode takes a variable to convert to javascript, and converts it to javascript
    • string json_encode(mixed $variable)
    • Parameters:
      • $variable can be any type except a PHP resource
      Return Values:
      • It will return a string with the Javascript equivalent. You can then echo it out into Javascript, or use eval(), very, very, very, very, carefully, in Javascript
      Examples:
      <?php
      	$array=array(5,1,7,2,8,3);
      
      	$javascript=json_encode($array);
      	echo "$javascript <br>";
      	echo "<script type='text/javascript'>var array=$javascript</script>";
      
      	//Returns a Javascript array:
      	
      	[5,1,7,2,8,3] 
      ?>
      <?php
      	class example{
      		public hello="hola";
      		public bye="adios";
      	}
      	$ex=new example();
      	echo $jsex=json_encode($ex);
      	echo "<script type='text/javascript'>var example=$jsex;document.write(example.hello)</script>"
      	
      	//Returns:
      	
      	
      	{"hello":"hola","bye":"adios"}
      		
      	
      
      ?>

  • json_decode

    • json_decode does the opposite of json_encode. It takes a Javascript object and converts it to a PHP object
    • mixed json_decode(string $javascript, [bool $associative_array])
    • Parameters:
      • string $javascript: A JSON string
      • bool $associative_array: Optional. Default false. Whether to return an object as an associative array.
      Return Values:
      • If the conversion fails, it returns false
      • Otherwise, it returns the PHP counterpart of the Javascript object
      Examples:
      <?php
      	$js="[1,7,3,8,3]"; //Javascript array
      	$phparray=json_decode($js);
      	print_r $phparray; 
      	
      	//Returns:
      		
      	Array
      (
          [0] => 1
          [1] => 7
          [2] => 3
          [3] => 8
          [4] => 3
      )
      
      >