PHP JSONz

Posted May 28, 2010

At my place of work, much of the URLs we use internal to the system uses JSON-encoded objects which are BASE64 encoded in order to be able to use them as part of the path in a URL. The major advantage of this is that we can pass huge amounts of arguments with meaningful names a lot easier than using simple REST, and more SEO friendly than using HTTP parameters.

However, we had 2 drawbacks:

  1. as more parameters were being passed in the JSON, the URLs start becoming huge
  2. some environments (such as Facebook Connect) do not like URLs which contain the '=' character

As an interesting side-effect, because JSON only contains ASCII characters, BASE64 encoding never generated the '/' character, which would have thrown the whole thing into turmoil.

To overcome the 2 issues above, I created "jsonz" encoding and decoding functions (jsonz meaning JSON Gzipped).

 

<?php
/**
 * Converts a value into a JSON string which is GZip deflated, BASE64 encoded,
 * and URL-encoded. This is intended to be suitable for URL-embedding, and
 * reducing size of straight BASE64 encoding of a JSON string.
 * <p>
 * Note that the size reduction is best with larger objects - as the resulting
 * JSON string becomes smaller, the result may actually be a few bytes larger
 * than simply BASE64 encoding.
 *
 * @param mixed $value value to convert to a JSON string
 * @return string result
 */
function jsonz_encode($value) {
    return urlencode(
            base64_encode(
                    gzdeflate(
                            json_encode($value), 9
                            )
                    )
            );
}

/**
 * Decodes a value previously encoded using jsonz_encode
 *
 * @param string $json encoded string to decode
 * @return mixed result
 * @see jsonz_encode
 */
function jsonz_decode($json) {
    return json_decode(
            gzinflate(
                    base64_decode(
                            urldecode($json)
                            )
                    )
            );
}
?>

Something to make note of - if your JSON string is rather small (say 12 bytes), then GZipping will actually increase the size marginally (from my tests, by 1 or 2 bytes only).

By implicitly adding the URL-encoding, the result becomes URL-safe.

As a simple comparison, a JSON string of 141 bytes long encoded with just BASE64 resulted in a string 188 bytes long. The same JSON string encoded using jsonz_encode resulted in a string 152 bytes long. 36 byte saving ain't bad!

Comments

Thank you so much for explaining this. I was totally unaware of this issue on Facebook. I was just checking some of my past blogs and found you there. My apologies for never seeing that. Awesome blog Lani, Will be checking back to you soon.

Displaying 1 comment

Add comment

Visit my Friends and Family

If you've enjoyed my site, please take a moment to visit my friends and family, many of whom have some interesting insights, and entertaining thoughts and ideas.