how to check if json php code example
Example 1: php if is json object
if (is_object(json_decode($var))) {
....
}
var $x = json_decode($var);
var $y = is_object($x)?$x:....;
function json_validate($string) {
$result = json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = '';
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;
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
break;
case JSON_ERROR_RECURSION:
$error = 'One or more recursive references in the value to be encoded.';
break;
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 !== '') {
exit($error);
}
return $result;
}
$output = json_validate($json);
Example 2: php is json
function is_json($input_line) {
if(is_string($input_line)){
preg_match('/^\{(\s+|\n+)*(\"(.*)(\n+|\s+)*)*\}$|^\[(\s+|\n+)*\{(\s+|\n+)*(\"(.*)(\n+|\s+)*)*\}(\s+|\n)*\]$/', $input_line, $output_array);
if ( isset($output_array) || !empty($output_array)) {
return true;
}
}
return false;
}