You receive a data in form of string and it is supposed to be a valid JSON. So how to know whether a string you have is a valid JSON object. Here in this post I will show it with some examples to how to check whether a string is a valid json value in PHP.
Using json_encode() function
You already know that we use json_decode()
to decode a JSON string. However you may not know about the json_last_error can be used to detect last json parse error in the current PHP parser. If there is any error, calling json_last_error will have a code different than JSON_ERROR_NONE’s value, that is 0.
Example:
function is_valid_json($str) { json_decode($str); return json_last_error() === JSON_ERROR_NONE; } $json_str = '{"a":"Apple","b":"Banana"}'; if (is_valid_json($json_str)) { echo 'String is a valid JSON'; } else { echo 'String is not a valid JSON'; }
Since JSON_ERROR_NONE
constant has stored 0 as a value and if there is no error json_last_error()
will return 0. can have following values, as explained here:
0 = JSON_ERROR_NONE 1 = JSON_ERROR_DEPTH 2 = JSON_ERROR_STATE_MISMATCH 3 = JSON_ERROR_CTRL_CHAR 4 = JSON_ERROR_SYNTAX 5 = JSON_ERROR_UTF8