I need a really, really fast method of checking if a string is JSON or not. I feel like this is not the best way:
function isJson($string) { return ((is_string($string) && (is_object(json_decode($string)) || is_array(json_decode($string))))) ? true : false; }
Any performance enthusiasts out there want to improve this method?
To determine if the JSON output is genuine, PHP includes a method called json_decode(), which was introduced in PHP 5.3. It is a PHP built-in function that is used to decode a JSON string. It creates a PHP variable from a JSON encoded text.
In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.
JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.
The unofficial MIME type " text/json " or the content-type " text/javascript " are also supported for legacy reasons by many service providers, browsers, servers, web applications, libraries, frameworks, and APIs.
function isJson($string) { json_decode($string); return json_last_error() === JSON_ERROR_NONE; }
Answer to the Question
The function json_last_error
returns the last error occurred during the JSON encoding and decoding. So the fastest way to check the valid JSON is
// decode the JSON data // set second parameter boolean TRUE for associative array output. $result = json_decode($json); if (json_last_error() === JSON_ERROR_NONE) { // JSON is valid } // OR this is equivalent if (json_last_error() === 0) { // JSON is valid }
Note that json_last_error
is supported in PHP >= 5.3.0 only.
Full program to check the exact ERROR
It is always good to know the exact error during the development time. Here is full program to check the exact error based on PHP docs.
function json_validate($string) { // decode the JSON data $result = json_decode($string); // switch and check possible JSON errors switch (json_last_error()) { case JSON_ERROR_NONE: $error = ''; // JSON is valid // No error has occurred break; case JSON_ERROR_DEPTH: $error = 'The maximum stack depth has been exceeded.'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Invalid or malformed JSON.'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Control character error, possibly incorrectly encoded.'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON.'; break; // PHP >= 5.3.3 case JSON_ERROR_UTF8: $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.'; break; // PHP >= 5.5.0 case JSON_ERROR_RECURSION: $error = 'One or more recursive references in the value to be encoded.'; break; // PHP >= 5.5.0 case JSON_ERROR_INF_OR_NAN: $error = 'One or more NAN or INF values in the value to be encoded.'; break; case JSON_ERROR_UNSUPPORTED_TYPE: $error = 'A value of a type that cannot be encoded was given.'; break; default: $error = 'Unknown JSON error occured.'; break; } if ($error !== '') { // throw the Exception or exit // or whatever :) exit($error); } // everything is OK return $result; }
Testing with Valid JSON INPUT
$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]'; $output = json_validate($json); print_r($output);
Valid OUTPUT
Array ( [0] => stdClass Object ( [user_id] => 13 [username] => stack ) [1] => stdClass Object ( [user_id] => 14 [username] => over ) )
Testing with invalid JSON
$json = '{background-color:yellow;color:#000;padding:10px;width:650px;}'; $output = json_validate($json); print_r($output);
Invalid OUTPUT
Syntax error, malformed JSON.
Extra note for (PHP >= 5.2 && PHP < 5.3.0)
Since json_last_error
is not supported in PHP 5.2, you can check if the encoding or decoding returns boolean FALSE
. Here is an example
// decode the JSON data $result = json_decode($json); if ($result === FALSE) { // JSON is invalid }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With