Benoit Zohar

You Are Viewing

A Blog Post

Handle json_decode() errors

  • October 18, 2012
  • By
  • In PHP
  • No Comments

When you use the json_encode() function to parse a JSON file using PHP, do not expect to handle any Exception or to get any information if the parsing failed.

In order to handle errors, you will have to call json_last_error() if the result of json_encode() is NULL. NULL means that the data could not be parsed or you’ve reach the limit of recursion.

The thing is, json_last_error() returns a constant value. So, unless you love spending hours going through a log and translating the errors numbers, you’ll have to handle the error translation on-the-go.

Here’s a simple yet effective function which returns a full text version of the error:

function get_json_error() {
	switch (json_last_error()) {
		case JSON_ERROR_NONE: return 'No error';
		case JSON_ERROR_DEPTH: return 'Maximum recursion limit has been reached';
		case JSON_ERROR_STATE_MISMATCH: return 'Inadequate modes';
		case JSON_ERROR_CTRL_CHAR: return 'Special chars control error';
		case JSON_ERROR_SYNTAX: return 'Syntax error: JSON malformed';
		case JSON_ERROR_UTF8: return 'UTF8 chars are malformed; This might be an encoding problem';
	}
	return "Unknown Error";
}

And if you don’t want to handle errors using the dedicated method, you can use this function :

function json_decoder($json,$assoc = false,$depth = 512,$options = 0) {
	$decode_result = json_decode($json,$assoc = false,$depth = 512,$options = 0);
	if ($decode_result === NULL) {
		$err = 'Unknown Error';
		switch (json_last_error()) {
			case JSON_ERROR_NONE: 
				$err = 'No error'; 
			break;
			case JSON_ERROR_DEPTH: 
				$err =  'Maximum recursion limit has been reached';
			break;
			case JSON_ERROR_STATE_MISMATCH: 
				$err = 'Inadequate modes';
			break;
			case JSON_ERROR_CTRL_CHAR: 
				$err = 'Special chars control error';
			break;
			case JSON_ERROR_SYNTAX: 
				$err = 'Syntax error: JSON malformed';
			break;
			case JSON_ERROR_UTF8: 
				$err = 'UTF8 chars are malformed; This might be an encoding problem';
			break;
		}
		throw new Exception($err);
		return null;
	}
	
	return $decode_result;
}

And catch the Exception like this :

try {
	$parsed_data = json_decoder($data,true);
}
catch (Exception $e) {
	echo "An error happened while decoding the data : ".$e->getMessage();
}
Leave a Reply