Want to see something scary and hacky? Check this out – it takes in a PHP array and makes a JSON message out of it:
[php]
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)) ? ‘,’ : ”;
}
}
}
[/php]
And, of course, a sample of how to use it:
[php]
$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.’}’;
[/php]
Be afraid. Be very afraid 🙂
Why not simply use http://de.php.net/manual/en/function.json-encode.php 😉
LikeLike
Because that function only exists in CVS?
LikeLike
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 😉
LikeLike
wesley: http://pecl.php.net/package/json 🙂
LikeLike
Jaen – nicely done 🙂
*bows to the mastah*
LikeLike
http://pecl.php.net/package/json
And In the upcoming PHP 5.2 release the json extension should be included and enabled by default.
LikeLike
Now, if PHP 5.2 will just get here already 😉
LikeLike
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/
LikeLike
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
LikeLike