1function isJson($string) {
2 json_decode($string);
3 return (json_last_error() == JSON_ERROR_NONE);
4}
1//Simple
2if (is_object(json_decode($var))) {
3 ....
4}
5
6//Else
7var $x = json_decode($var);
8var $y = is_object($x)?$x:....;
9
10//Better
11function json_validate($string) {
12 // decode the JSON data
13 $result = json_decode($string);
14
15 // switch and check possible JSON errors
16 switch (json_last_error()) {
17 case JSON_ERROR_NONE:
18 $error = ''; // JSON is valid // No error has occurred
19 break;
20 case JSON_ERROR_DEPTH:
21 $error = 'The maximum stack depth has been exceeded.';
22 break;
23 case JSON_ERROR_STATE_MISMATCH:
24 $error = 'Invalid or malformed JSON.';
25 break;
26 case JSON_ERROR_CTRL_CHAR:
27 $error = 'Control character error, possibly incorrectly encoded.';
28 break;
29 case JSON_ERROR_SYNTAX:
30 $error = 'Syntax error, malformed JSON.';
31 break;
32 // PHP >= 5.3.3
33 case JSON_ERROR_UTF8:
34 $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
35 break;
36 // PHP >= 5.5.0
37 case JSON_ERROR_RECURSION:
38 $error = 'One or more recursive references in the value to be encoded.';
39 break;
40 // PHP >= 5.5.0
41 case JSON_ERROR_INF_OR_NAN:
42 $error = 'One or more NAN or INF values in the value to be encoded.';
43 break;
44 case JSON_ERROR_UNSUPPORTED_TYPE:
45 $error = 'A value of a type that cannot be encoded was given.';
46 break;
47 default:
48 $error = 'Unknown JSON error occured.';
49 break;
50 }
51
52 if ($error !== '') {
53 // throw the Exception or exit // or whatever :)
54 exit($error);
55 }
56 // everything is OK
57 return $result;
58}
59$output = json_validate($json);