This article describes how to determine whether php is in json format. For more information, 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:
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:
Function is_json ($ string) {www.jb51.net
Json_decode ($ string );
Return (json_last_error () = JSON_ERROR_NONE );
}
The json_last_error () function returns an error during data encoding/decoding.
Note: The json codec operation string must be UTF8
Example
The code is as follows:
/**
* 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.