JSON Page

  tonyperson  >  Home  >  code  >  json


Summary

Javascript Object Notation (JSON) is a great way to deliver your database or business logic in a human readable and native JavaScript manner. It is one of the less used Web 2.0 technologies but if you get your mind into it it will open up a way to make your code cleaner and keep your sanity (so atleast one of will be sane!). This method described below is a way PHP can manipulate incoming XML and translate and serve them to the client-side. There are other client-side ways of doing this but that is beyond the scope of this article.

This work is based on the foundation of JSON class created by Michal Migurski, Matt Knapp, and Brett Stimmerman.

Database

Here is a typical database query result array.

Array ( [a] => 1 [b1] => Array ( [1st] => 0 [2nd] => Array ( [4th] => 0 [5th] => 1 [6th] => 2 ) [third] => 2 ) [b2] => 3 [c] => Array ( [1st] => 0 ) [d] => 5 )

PHP Code

Here is the code I use to "Clean" the array and test for arrays within arrays. This will create a copy of the array to work on and the recurse as many levels as needed in the array.

//cleaner- a function- to allow "recursing";
function cleaner(&$array) {
foreach ($array as &$data) {
if (!is_array($data)) { //not an array
$data = $data;
}
else {
cleaner($data);
}
}
}
The function json_encode is a function included in the json_helper class that should be included in your code. The way to do that in codeignighter is to add a line in your Controller file or have it load automatically in your autoload.php file. //load your helper file
$this->load->helper('json');

Then the code I call to work the function in the Controller is:

$data['query'] = array('a'=>1, 'b1'=>array( '1st'=>0,'2nd'=>array( '4th'=>0,'5th'=>1,'6th'=>2),'third'=>2), 'b2'=>3, 'c'=>array( '1st'=>0,'2nd'=>1,'third'=>2), 'd'=>5);
$array = $data['query'];

$data['encoded_data'] = json_encode($array);
$this->load->view('json_view', $data);

JavaScript

Here is the Javascript.

//JavaScript
eval["var decoded_data = " + <?php echo $encoded_data; ?>];

JSON

Here is the JSON code.

{"a":1,"b1":{"1st":0,"2nd":{"4th":0,"5th":1,"6th":2},"third":2},"b2":3,"c":{"1st":0},"d":5}

Helpful Links

Check out the codeigniter article on JSON_Helper functionality -http://codeigniter.com/wiki/JSON_Helper

You may want to check out my page on XML to JSON transfomation- http://tonyperson.com/code/xml2json