Come determinare se una stringa è JSON valida?
-
19-09-2019 - |
Domanda
Qualcuno conosce uno snippet di funzione is_JSON robusto (e a prova di proiettile) per PHP?Io (ovviamente) ho una situazione in cui ho bisogno di sapere se una stringa è JSON o meno.
Hmm, forse eseguilo attraverso a JSONLint richiesta/risposta, ma sembra un po' eccessivo.
Soluzione
Se si utilizza il costruito nel json_decode
funzione PHP, < a href = "http://php.net/manual/en/function.json-last-error.php" rel = "noreferrer"> json_last_error
restituisce l'ultimo errore (ad esempio, JSON_ERROR_SYNTAX
quando la stringa wasn' t JSON).
json_decode
rendimenti null
comunque.
Altri suggerimenti
Cosa succede ad usare json_decode
, che dovrebbe restituire null
se la stringa data non era dati JSON con codifica validi?
Si veda l'esempio 3 nella pagina di manuale:
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
Per i miei progetti utilizzo questa funzione (leggi il "Nota" sul json_decode() documenti).
Passando gli stessi argomenti che passeresti a json_decode() puoi rilevare "errori" specifici dell'applicazione (ad es.errori di profondità)
Con PHP >= 5.6
// PHP >= 5.6
function is_JSON(...$args) {
json_decode(...$args);
return (json_last_error()===JSON_ERROR_NONE);
}
Con PHP >= 5.3
// PHP >= 5.3
function is_JSON() {
call_user_func_array('json_decode',func_get_args());
return (json_last_error()===JSON_ERROR_NONE);
}
Esempio di utilizzo:
$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
echo "Valid JSON string";
} else {
$error = json_last_error_msg();
echo "Not valid JSON string ($error)";
}
Non json_decode()
con un lavoro json_last_error()
per voi? Sei alla ricerca di solo un metodo per dire "Ti sembra JSON" o realmente convalidare esso? json_decode()
sarebbe l'unico modo per convalidare in modo efficace all'interno di PHP.
$this->post_data = json_decode( stripslashes( $post_data ) ); if( $this->post_data === NULL ) { die( '{"status":false,"msg":"The post_data parameter must be valid JSON"}' ); }
Questo è il modo migliore e più efficiente
function isJson($string) {
return (json_decode($string) == null) ? false : true;
}