Remember that json_encode returns a string, while json_decode returns an object.
Determine that the data is not in JSON format:
| The code is as follows: |
Copy code |
|
Function is_not_json ($ str ){
Return is_null (json_decode ($ str ));
} |
Determine that the data is legal json data: (PHP version is later than 5.3)
| The code is as follows: |
Copy code |
|
Function is_json ($ string ){
Json_decode ($ string );
Return (json_last_error () = JSON_ERROR_NONE );
} |
The json_last_error () function returns an error during the data encoding/decoding process.
Note: The json codec operation string must be UTF8.
Example
| The code is as follows: |
Copy code |
/**
* Parse json strings
* @ Param type $ json_str
* @ Return type
*/
Function analyJson ($ json_str ){
$ Json_str = str_replace ('\', '', $ json_str );
$ Out_arr = array ();
Preg_match ('/{. *}/', $ json_str, $ out_arr );
If (! Empty ($ out_arr )){
$ Result = json_decode ($ out_arr [0], TRUE );
} Else {
Return FALSE;
}
Return $ result;
} |
If it is not json, false is returned.