Created
June 12, 2011 19:59
-
-
Save alkavan/1021933 to your computer and use it in GitHub Desktop.
JSON Helper for Kohana v3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php defined('SYSPATH') or die('No direct script access.'); | |
/** | |
* JSON helper class | |
* | |
* Examples: | |
* $j = JSON::decode('{"Organization": "Kohana"}'); // Good | |
* $j = JSON::decode("{'Organization': 'Kohana'}"); // Invalid | |
* $j = JSON::decode('{"Organization": "Kohana"}', NULL, 1); // depth stack exceeded | |
* | |
* @package Kohana | |
* @category Helpers | |
* @author Igal Alkon <igal.alkon@gmail.com> | |
*/ | |
class JSON | |
{ | |
/** | |
* Returns a string containing the JSON representation of value | |
* Please note: | |
* PHP 5.3.0 - The options parameter was added. | |
* PHP 5.2.1 - Added support for JSON encoding of basic types. | |
* | |
* @static | |
* @param mixed $value This function only works with UTF-8 encoded data | |
* @return string | |
*/ | |
public static function encode($value) | |
{ | |
return json_encode($value); | |
} | |
/** | |
* Takes a JSON encoded string and converts it into a PHP variable | |
* Please note: | |
* PHP future - The options parameter was added | |
* PHP 5.3.0 - Added the optional depth. The default recursion depth was increased from 128 to 512 | |
* PHP 5.2.3 - The nesting limit was increased from 20 to 128 | |
* | |
* @static | |
* @throws Kohana_Exception | |
* @param string $json This function only works with UTF-8 encoded data | |
* @param bool $to_assoc When TRUE, returned objects will be converted into associative arrays | |
* @param int $depth User specified recursion depth | |
* @return mixed | |
*/ | |
public static function decode($json, $assoc = FALSE, $depth = 512) | |
{ | |
$result = json_decode($json, $assoc, $depth); | |
switch(json_last_error()) | |
{ | |
case JSON_ERROR_DEPTH: | |
$error = 'Maximum stack depth exceeded'; | |
break; | |
case JSON_ERROR_CTRL_CHAR: | |
$error = 'Unexpected control character found'; | |
break; | |
case JSON_ERROR_STATE_MISMATCH: | |
$error = 'Invalid or malformed JSON'; | |
break; | |
case JSON_ERROR_SYNTAX: | |
$error = 'Syntax error'; | |
break; | |
case JSON_ERROR_NONE: | |
default: | |
$error = ''; | |
} | |
if ( ! empty($error)) | |
{ | |
throw new Kohana_Exception('JSON DECODE: :error', array(':error' => $error)); | |
} | |
return $result; | |
} | |
} // End JSON |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment