A Single-function JSON Freakshow
Want to see something scary and hacky? Check this out – it takes in a PHP array and makes a JSON message out of it:
function build($arr,&$str,$lvl=0,$in_arr=''){
$lvl++;
foreach($arr as $key => $value){
if(is_array($value)){
$str.=(($in_arr==1)?'{':'').'"'.$key.'": ';;
if(count($value)>1){ $str.='[';
}elseif(count($value)==1){ $str.='';
}else{ $str.='{'; }
build($value,$str,$lvl,1);
if(count($value)>1){ $str.=']';
}elseif(count($value)==1){ $str.='';
}else{ $str.='}'; }
$str.=($in_arr==1) ? '}' : '';
$str.=(next($arr)) ? ',' : '';
}else{
$str.=($lvl>1) ? '{' : '';
$str.='"'.$key.'":"'.$value.'"';
$str.=($lvl>1) ? '}' : '';
$str.=(next($arr)) ? ',' : '';
}
}
}
And, of course, a sample of how to use it:
$my_data=array(
"foo"=>"1",
"bar"=>"2",
"baz"=>array(
"one"=>"1",
"two"=>"2"
),
"test"=>array(
"my_test"=>array(
"one_more"=>"1","three_more"=>"test"
),
"your_test"=>array(
"two_more"=>"2"
),
"nest1"=>array(
"nest2"=>array(
"nest"=>"test"
)
)
),
"meedle"=>"squeedle"
);
$str='';
build($my_data,$str);
echo '{'.$str.'}';
Be afraid. Be very afraid
Category: PHP 9 comments »
September 23rd, 2006 at 8:49 am
Why not simply use http://de.php.net/manual/en/function.json-encode.php
September 23rd, 2006 at 8:56 am
Because that function only exists in CVS?
September 23rd, 2006 at 11:04 am
Does not handle quoting (slashes) and Unicode escapes, I would be very afraid to use it in real code
You might try this on for size though:
function j($x, $y = null) {
if($y) return j($x).":".j($y);
if(is_array($x)) {
$a = ($k = array_keys($x)) == range(0, count($x) - 1);
return ($a?'[':'{').implode(', ',
$a ? array_map('j', $x) : array_map('j', $k, array_values($x))).
($a?']':'}');
}
return '"'.addslashes($x).'"';
}
I have a shorter version but that’s almost completely unreadable
September 23rd, 2006 at 11:14 am
wesley: http://pecl.php.net/package/json
September 23rd, 2006 at 12:09 pm
Jaen – nicely done
*bows to the mastah*
September 23rd, 2006 at 12:36 pm
http://pecl.php.net/package/json
And In the upcoming PHP 5.2 release the json extension should be included and enabled by default.
September 23rd, 2006 at 12:39 pm
Now, if PHP 5.2 will just get here already
September 25th, 2006 at 1:09 am
Any function to parse JSON?
I have written a small function that would take an SQL query as an argument and return the result in JSON.
http://www.bin-co.com/php/scripts/sql2json/
October 10th, 2006 at 1:36 pm
enygma and Jaen, have you checked what happens if, for example, “meedleâ€=>Ҡ?
Binny V A, for a JSON parser go to http://www.json.org/js.html