Sunday, June 14, 2009

JSON generation with PHP and parsing with jQuery

JSON [official site][wiki] is a data interchange format (similar to XML, but simpler), often used for WEB 2.0 applications to load structured data with AJAX HTTP calls.
- PHP offers functions to encode and decode JSON from/to a PHP value.
- jQuery includes a function (getJSON) to parse HTTP resource with JSON data.

JSON pseudo grammar
#json block: comma separated couple key: value
JSON_BLOCK = { KEY1: VALUE1, KEY2: VALUE2, ..., KEY_N: VALUE_N }
#key must be a string (example: "abc123")
KEY_N = string
# value must be a native type, or array of values or json_block (recursive)
VALUE_N = string | number | true | false | null |
| [
VALUE_N,..., VALUE_N] |JSON_BLOCK

Minimal example:
//note: "less/greater than" symbols are replaced with square brackets because of blogspot limitation

/* json.php - json generation */
print json_encode( array(
"title" => "products",
"items"=> array(
array(
"id"=>"1","title"=>"1st"),
array(
"id"=>"2","title"=>"2nd")
)));
/*
result ("items" key contains an array with two values, each one is a block).
{
"title":"products",
"items": [ {"id":"1","title":"1st"}, {"id":"2","title":"2nd"} ]
}
*/


/* page.html - call JSON resource (ajax with jQuery) and write into the DOM*/
[script src="jquery-1.3.2.min.js" ][/script]
[
script]
$(
document).ready(function(){
$.
getJSON("json.php",
function(
data){
$.
each(data.items, function(i,item){
$(
"[h1]").text(item.id).appendTo("#main");
$(
"[h4]").text(item.title).appendTo("#main");
});
});
});
[/
script]
[
body]
[
div id="main" ][/div]
[/
body]

//output:
[body]
[
div id="main"
[h1]1[h1] [h4]1st[h4]
[
h1]2[h1] [h4]2nd[h4]
[/
div]
[/
body]

1 comment:

 

PHP and tips|PHP