Saturday, January 26, 2008

Json Encoding

For a enterprising young developer like myself, i don't take advantage of json enough. So since i'm in the mix at the moment, with my DFTI course work, i thought now would be a good time.

Unfortunately the json_encode() function that i had seen in the PHP documentation, is only in the CVS distributions at the moment (v 5.1.2), so i came up with the below.

PHP

/*
This function converts an array to a Json string.
*/
function jsonEncode( $pArr ){
$arr = Array('{');

foreach( $pArr as $val ){

if( is_numeric( $val) ){
array_push($arr, $val );
}else{
array_push($arr, '"');
array_push($arr, $val);
array_push($arr, '"');
}
array_push($arr,',');
}
//Remove trailing comma
array_pop($arr);

return implode('',$arr);
}

/*
This function converts an associative array to a Json string.
*/
function jsonEncodeAssoc( $pArr ){
$arr = Array('{');

foreach( $pArr as $key => $val){
array_push($arr, '"');
array_push($arr, $key);
array_push($arr, '"');
array_push($arr, ':');

if( is_numeric( $val ) ){
array_push($arr, $val);
}
else{
array_push($arr, '"');
array_push($arr, $val);
array_push($arr, '"');
}

array_push($arr, ',');
}

//Remove trailing comma
array_pop($arr);

array_push($arr,'}');

return implode('',$arr);
}


Both functions take either a regular array, or a Associative and converts it to a json string, which looks like ...


{"id":1,"name":"Ham And Pineapple","description":"<p>Fusce magna sem, gravida in, feugiat ac, molestie eget, wisi.</p>","categoryId":1,"hasNuts":0,"vegetarians":0,"imagePath":"ham-and-pineapple.gif","price":4.95}



The above is just some data from my database. It's a pizza ordering system. I plan to go all ajaxan with a Drag and drop shopping cart, as well as some other shiny stuff.

I haven't a clue what i'm going to do concerning javascript, i'm looking at mootools, mochikit, and of course jquery and maybe even yahoo ui. Might be a last minute thing.

No comments: