Memoirs of a Programmer


uJSON - Micro JSON

Just a little shout out to the programming world...

If you would like to include JSON requests inside of a URL, you'll notice a couple hindering points, including the fact that IE and Firefox (or any browser for that matter) dislikes anything after the ? in the URL to contain quotes, or else it converts all of that using URL encoding, which just makes the url longer and less appealing. So I went along and made a little extension of the well known Services_JSON package which basically converts the JSON string, removing the quotes. The extension has both an encoder and a decoder. Any comments would be great.



<?
/*
This converts a slimmer version of a json into normal json and vice versa

Values must not contain {}[] or ,

Quite useful if you want to have json requests inside of a url

( i.e. http://www.yourdomain.com/index.php?request=[array_element,{object:value}] )
*/
class Micro_Json extends Services_JSON
{
function decodeMini($string)
{
$result = preg_replace('/([^{}:\\[\\],]+)/', '"${1}"', $string);
$result = $this->decode($result);
return $result;
}

function encodeMini($object)
{
$object = $this->optimize($object);
if(count($object) == 0)
return "";
$result = $this->encode($object);
$result = preg_replace('/((?<!\\\\)")/', '', $result);
return $result;
}

private function optimize($object, $reorder = false, $sub_reorder = false)
{
if($reorder)
$new_object = array();

if(isset($object) && is_array($object))
{
foreach ($object as $key => &$value)
{
if(is_array($value) || is_object($value))
$value = optimize($value, $sub_reorder, $sub_reorder);

if(!isset($value) || empty($value) || $value == null || count($value) == 0)
{
unset($object[$key]);
}
else
{
//Attach to new array if reorder is true
if($reorder)
$new_object[] = &$value;
}
}
}

if($reorder)
$object = $new_object;

if(is_object($object) && count(get_object_vars($object)) == 0)
{
$object = null;
}
if(count($object) == 0 || empty($object))
{
$object = null;
}

return $object;
}
}

?>



If you would like to download the file, you can through this link. Just rename the extension to php, and you're done (be sure you have Services_JSON lying around).

I'm not that great at explaining my own stuff, probably because it's all old to me now, but if you have questions, leave a comment or drop me a message at floydroute@gmail.com.

0 Responses to “uJSON - Micro JSON”

Post a Comment