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 »

9 Responses to “A Single-function JSON Freakshow”

  1. Toby

    Why not simply use http://de.php.net/manual/en/function.json-encode.php ;)

  2. wesley

    Because that function only exists in CVS?

  3. Jaen

    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 ;)

  4. bjori

    wesley: http://pecl.php.net/package/json :)

  5. enygma

    Jaen – nicely done :)
    *bows to the mastah*

  6. Jens

    http://pecl.php.net/package/json

    And In the upcoming PHP 5.2 release the json extension should be included and enabled by default.

  7. enygma

    Now, if PHP 5.2 will just get here already ;)

  8. Binny V A

    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/

  9. José Rui Abreu Mira

    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


Leave a Reply



Back to top