Hoe controleren of een string een geldige JSON string is in JavaScript zonder Try/Catch te gebruiken

Zoiets als:

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

//should be true
IsJsonString(jsonString);

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

De oplossing zou geen try/catch moeten bevatten. Sommigen van ons zetten "break on all errors" aan en die willen niet dat de debugger breekt op die ongeldige JSON strings.

Gebruik een JSON parser zoals JSON.parse:

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

In prototypeJS, hebben we methode isJSON. U kunt dat proberen. Zelfs json zou kunnen helpen.

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

U kunt de javascript eval() functie gebruiken om te controleren of het'geldig is.

bijv.

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
}

Als alternatief kun je de JSON.parse functie van json.org gebruiken:

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

if (json) {
  //this is json
}

Hopelijk helpt dit.

WAARSCHUWING: eval() is gevaarlijk als iemand kwaadaardige JS code toevoegt, aangezien het deze zal uitvoeren. Zorg ervoor dat de JSON String betrouwbaar is, d.w.z. dat je het van een betrouwbare bron hebt.

Edit Voor mijn 1e oplossing is het'aan te raden om dit te doen.

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

Om garantie te geven op json-ness. Als de jsonString niet zuiver JSON is'zal de eval een exception gooien.

Commentaren (11)