Come controllare se una stringa è una stringa JSON valida in JavaScript senza usare Try/Catch

Qualcosa come:

var jsonString = '{ "Id": 1, "Name": "Coke" }';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")

La soluzione non dovrebbe contenere try/catch. Alcuni di noi attivano "break on all errors" e non gli piace che il debugger si interrompa su quelle stringhe JSON non valide.

Usa un parser JSON come JSON.parse:

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
Commentari (14)

In prototypeJS, abbiamo il metodo isJSON. Puoi provare quello. Anche json potrebbe aiutare.

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
Commentari (5)

Puoi usare la funzione javascript eval() per verificare se è valida.

Per esempio

var jsonString = '{ "Id": 1, "Name": "Coke" }';
var json;

try {
  json = eval(jsonString);
} catch (exception) {
  //It's advisable to always catch an exception since eval() is a javascript executor...
  json = null;
}

if (json) {
  //this is json
}

In alternativa, puoi usare la funzione JSON.parse di json.org:

try {
  json = JSON.parse(jsonString);
} catch (exception) {
  json = null;
}

if (json) {
  //this is json
}

Spero che questo aiuti.

AVVERTENZA: eval() è pericoloso se qualcuno aggiunge codice JS malevolo, poiché lo eseguirà. Assicuratevi che la stringa JSON sia affidabile, cioè l'avete ottenuta da una fonte affidabile.

Modifica Per la mia 1a soluzione, si raccomanda di fare questo.

 try {
      json = eval("{" + jsonString + "}");
    } catch (exception) {
      //It's advisable to always catch an exception since eval() is a javascript executor...
      json = null;
    }

Per garantire la jsonità. Se la jsonString non è JSON puro, l'eval lancerà un'eccezione.

Commentari (11)