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:

[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 🙂

Advertisement

9 comments

  1. 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 😉

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s