Elegant little PHP JSON encoder

update: Jay Williams has flushed this out to be a lot more useful. Check out his rendition here.

…so I wrote (what I think is a) clever little function (well, two functions) to take a complex php variable and turn it into a json-ized string, ready to be passed back to javascript. It works on the principle that json really only has a couple rules if text formatting: strings go inside double quotes, with both slashes and double-quotes escaped, iterative arrays are comma delimited inside brackets [obj1,obj2], and associative arrays go inside curly-brackets {key:val,key:val}. Using these three points, and a little bit (ok, a lot of) recursion, and voila, an elegant little function.

Of course, this doesn’t handle unicode, or any really special cases, but if you’re looking for a basic object parser, and you dont’ have access to php 5.2, which has it built into the language, it’ll do the trick…

 * input an object, returns a json-ized string of said object
 * @return
 * @param $obj Object
function php_json_encode($obj) {
	if (is_array($obj)) {
		if (array_is_associative($obj)) {
			$arr_out = array();
			foreach ($obj as $key=>$val) {
				$arr_out[] = '"' . $key . '":' . php_json_encode($val);
			return '{' . implode(',', $arr_out) . '}';
		} else {
			$arr_out = array();
			$ct = count($obj);
			for ($j = 0; $j < $ct; $j++) {
				$arr_out[] = php_json_encode($obj[$j]);
			return '[' . implode(',', $arr_out) . ']';
	} else {
		if (is_int($obj)) {
			return $obj;
		} else {
			$str_out = stripslashes(trim($obj));
			$str_out = str_replace(array('"', '', '/'), array('\"', '\', '/'), $str_out);
			return '"' . $str_out . '"';


function array_is_associative($array) {
	$count = count($array);
	for ($i = 0; $i < $count; $i++) {
		if (!array_key_exists($i, $array)) {
			return true;
	return false;

tags: , , , , ,
posted in ajax, coding, json, php by chip

Follow comments via the RSS Feed | Leave a comment

4 Comments to "Elegant little PHP JSON encoder"

  1. JessicaSophia wrote:

    I am married to a geek.

  2. Jay Williams wrote:

    Handy little function. I’ve found though that It didn’t handle boolean and floats too well, so I’ve extended and restructured it a bit, you can see the changes here:

    Also, is this code licensed under? I’d like to use it in an Open Source project but I’d like to make sure it’s free first.


  3. chip wrote:

    Hey Jay –

    Yeah, that makes it much more useful. I’ve added a note to the top of the post for future googlers.

    It’s licensed under, um, uh, the one where I get lots of money? No, I’m kidding – feel free to use it with whatever attribution you like, and thanks for making the function better!

  4. Matt G wrote:

    What a great little function! The internal json_encode() is only good on PHP 5.2 or higher, this is great for building backwards compatible code. Bravo!

Leave Your Comment


Powered by Wordpress and MySQL. Theme by openark.org