note 104468 added to function.json-last-error

From: Date: Thu, 16 Jun 2011 15:33:23 +0000
Subject: note 104468 added to function.json-last-error
Groups: php.notes 
Request: Send a blank email to php-notes+get-180616@lists.php.net to get a copy of this message
Making lior's class a little more robust: <?php /** * * JSON wrapper class that handles JSON encoding/decoding errors. * * @see http://us.php.net/manual/en/function.json-last-error.php * * @author rynop http://rynop.com * */ class JSON { /** * * Encode String to JSON * @param mixed $obj * @return string JSON representation * @throws Exception */ public static function Encode($obj) { $result = json_encode($obj); self::checkForErrors(); return $result; } /** * * Decodes a JSON string * @param string $json * @param boolean $toAssoc * @return Object JSON Object * @throws Exception */ public static function Decode($json, $toAssoc = false) { $result = json_decode($json, $toAssoc); self::checkForErrors(); return $result; } private static function checkForErrors(){ $code = json_last_error(); switch($code) { case JSON_ERROR_DEPTH: $error = 'Maximum stack depth exceeded'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Invalid or malformed JSON'; break; case JSON_ERROR_NONE: default: $error = ''; } if (!empty($error)){ throw new Exception('JSON Error: '.$error,$code); } } } ?> ---- Server IP: 208.69.120.55 Probable Submitter: 68.115.89.192 ---- Manual Page -- http://www.php.net/manual/en/function.json-last-error.php Edit -- https://master.php.net/note/edit/104468 Del: integrated -- https://master.php.net/note/delete/104468/integrated Del: useless -- https://master.php.net/note/delete/104468/useless Del: bad code -- https://master.php.net/note/delete/104468/bad+code Del: spam -- https://master.php.net/note/delete/104468/spam Del: non-english -- https://master.php.net/note/delete/104468/non-english Del: in docs -- https://master.php.net/note/delete/104468/in+docs Del: other reasons-- https://master.php.net/note/delete/104468 Reject -- https://master.php.net/note/reject/104468 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#180616) next »