Jak sprawdzić, czy ciąg jest poprawnym ciągiem JSON w JavaScript bez użycia Try/Catch

Coś w stylu:

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

//should be true
IsJsonString(jsonString);

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

Roztwór nie powinien zawierać try/catch. Niektórzy z nas włączają "break on all errors" i nie lubią, gdy debugger łamie te nieprawidłowe ciągi JSON.

Author: Chris Martin, 2010-09-14

18 answers

najpierw komentarz. Pytanie dotyczyło nie używania try/catch.
Jeśli nie masz nic przeciwko, aby go użyć, Przeczytaj odpowiedź poniżej. Tutaj po prostu sprawdzamy JSON string używając wyrażenia regularnego, i będzie to działać w większości przypadków, nie we wszystkich przypadkach.

Rozejrzyj się po linii 450 W https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Istnieje wyrażenie regularne, które sprawdza poprawność JSON, coś w stylu:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

  //the json is ok

}else{

  //the json is not ok

}

EDIT : nowa wersja json2.js robi a bardziej zaawansowane parsowanie niż wyżej, ale nadal oparte na regexp replace (z komentarz @Mrchief )

 118
Author: Mic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-09 13:59:06

Użyj parsera JSON jak JSON.parse:

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
 632
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-14 15:11:15

wiem, że jestem 3 lata spóźniony na to pytanie, ale miałem ochotę się wtrącić.

Chociaż rozwiązanie Gumbo działa świetnie, nie obsługuje kilku przypadków, w których nie ma wyjątku dla JSON.parse({something that isn't JSON})

Wolę również zwracać parsowany JSON w tym samym czasie, więc kod wywołujący nie musi wywoływać JSON.parse(jsonString) po raz drugi.

To chyba działa dobrze na moje potrzeby:

function tryParseJSON (jsonString){
    try {
        var o = JSON.parse(jsonString);

        // Handle non-exception-throwing cases:
        // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
        // but... JSON.parse(null) returns null, and typeof null === "object", 
        // so we must check for that, too. Thankfully, null is falsey, so this suffices:
        if (o && typeof o === "object") {
            return o;
        }
    }
    catch (e) { }

    return false;
};
 364
Author: Matt H.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-15 09:01:27
// vanillaJS
function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

Użycie: isJSON({}) będzie false, isJSON('{}') będzie true.

Aby sprawdzić, czy coś jest Array lub Object (parsed JSON):

// vanillaJS
function isAO(val) {
    return val instanceof Array || val instanceof Object ? true : false;
}

// ES2015
var isAO = (val) => val instanceof Array || val instanceof Object ? true : false;

Użycie: isAO({}) będzie true, isAO('{}') będzie false.

 41
Author: moeiscool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-24 00:06:32

W prototypie js mamy metodę isJSON. try that

Http://api.prototypejs.org/language/string/prototype/isjson/

Even http://www.prototypejs.org/learn/json

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
 11
Author: Ifi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-14 15:13:10

Użyłem bardzo prostej metody, aby sprawdzić ciąg znaków, czy jest to poprawny JSON, czy nie.

function testJSON(text){
    if (typeof text!=="string"){
        return false;
    }
    try{
        JSON.parse(text);
        return true;
    }
    catch (error){
        return false;
    }
}

Wynik z poprawnym łańcuchem JSON:

var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;

Wynik za pomocą prostego ciągu;

var input='This is not a JSON string.';
testJSON(input); // returns false;

Wynik z obiektem:

var input={};
testJSON(input); // returns false;

Wynik z NULL input:

var input=null;
testJSON(input); // returns false;

Ostatni zwraca false, ponieważ typem zmiennych null jest object.

To działa za każdym razem. :)
 9
Author: kukko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-16 08:41:50

From Prototype framework String.isJSON definition here

/**
   *  String#isJSON() -> Boolean
   *
   *  Check if the string is valid JSON by the use of regular expressions.
   *  This security method is called internally.
   *
   *  ##### Examples
   *
   *      "something".isJSON();
   *      // -> false
   *      "\"something\"".isJSON();
   *      // -> true
   *      "{ foo: 42 }".isJSON();
   *      // -> false
   *      "{ \"foo\": 42 }".isJSON();
   *      // -> true
  **/
  function isJSON() {
    var str = this;
    if (str.blank()) return false;
    str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
    str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
    return (/^[\],:{}\s]*$/).test(str);
  }

Więc jest to wersja, która może być użyta przekazując obiekt string

function isJSON(str) {
    if ( /^\s*$/.test(str) ) return false;
    str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
    str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
    return (/^[\],:{}\s]*$/).test(str);
  }

function isJSON(str) {
    if ( /^\s*$/.test(str) ) return false;
    str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
    str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
    return (/^[\],:{}\s]*$/).test(str);
  }

console.log ("this is a json",  isJSON( "{ \"key\" : 1, \"key2@e\" : \"val\"}" ) )

console.log("this is not a json", isJSON( "{ \"key\" : 1, \"key2@e\" : pippo }" ) )
 4
Author: loretoparisi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-07 11:48:06

Możesz użyć funkcji javascript eval(), aby sprawdzić, czy jest poprawna.

Np.

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
}

Alternatywnie możesz użyć funkcji JSON.parse z json.org :

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

if (json) {
  //this is json
}
Mam nadzieję, że to pomoże.

Ostrzeżenie: eval() jest niebezpieczne jeśli ktoś doda złośliwy kod JS, ponieważ go wykona. Upewnij się, że łańcuch JSON jest godny zaufania, tzn. otrzymałeś go z zaufanego źródła.

Edit dla mojego pierwszego rozwiązania, to zalecane, aby to zrobić.

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

Do Gwarancja json-ness. Jeśli jsonString nie jest czystym JSON, eval rzuci wyjątek.

 3
Author: Buhake Sindi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-11 09:42:05

Ta odpowiedź, aby zmniejszyć koszt wyciągu trycatch.

Użyłem JQuery do parsowania łańcuchów JSON i użyłem instrukcji trycatch do obsługi wyjątków, ale rzucanie wyjątków dla nie-parsowalnych łańcuchów spowolniło mój kod, więc użyłem prostego wyrażenia regularnego, aby sprawdzić łańcuch, czy jest to możliwy łańcuch JSON, czy nie, bez sprawdzania jego składni, a następnie użyłem regularnego sposobu parsowania łańcucha za pomocą JQuery:

if (typeof jsonData == 'string') {
    if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
        return jsonData;
    }
}

try {
    jsonData = $.parseJSON(jsonData);
} catch (e) {

}

Zawinąłem poprzedni kod w funkcja rekurencyjna do analizy zagnieżdżonych odpowiedzi JSON.

 3
Author: Rabih,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-25 08:32:56

Może się przyda:

    function parseJson(code)
{
    try {
        return JSON.parse(code);
    } catch (e) {
        return code;
    }
}
function parseJsonJQ(code)
{
    try {
        return $.parseJSON(code);
    } catch (e) {
        return code;
    }
}

var str =  "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
alert(typeof parseJson(str));
alert(typeof parseJsonJQ(str));
var str_b  = "c";
alert(typeof parseJson(str_b));
alert(typeof parseJsonJQ(str_b));

Wyjście:

IE7: string , object, string, string

CHROME: object,object,string, string

 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-05 11:40:30

Chyba wiem, dlaczego chcesz tego uniknąć. Ale może spróbuj i złap != = try & catch = = ;o) przyszło mi to do głowy:

var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

Więc można również sproszkować obiekt JSON, np.:

JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

Ponieważ jest to jak najbardziej zamknięte, może nie pęknąć na błąd.

 2
Author: chrixle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-10 18:38:50
function get_json(txt)
{  var data

   try     {  data = eval('('+txt+')'); }
   catch(e){  data = false;             }

   return data;
}

Jeśli są błędy, zwróć false.

Jeśli nie ma błędów, zwróć json data

 1
Author: Emrah Tuncel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-06 03:38:10

var jsonstring='[{"ConnectionString":"aaaaaa","Server":"ssssss"}]';

if(((x)=>{try{JSON.parse(x);return true;}catch(e){return false}})(jsonstring)){

document.write("valide json")

}else{
document.write("invalide json")
}
 1
Author: safi eddine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-01 16:33:21

Wnioskuję z komentarza otwierającego, że przypadek użycia określa, czy odpowiedzią jest HTML czy JSON. W takim przypadku, kiedy odbierasz JSON, prawdopodobnie powinieneś go parsować i obsługiwać nieprawidłowy JSON w pewnym momencie swojego kodu. Pomijając cokolwiek, wyobrażam sobie, że chciałbyś być informowany przez przeglądarkę, czy JSON powinien być oczekiwany, ale nieprawidłowy JSON otrzymany (podobnie jak użytkownicy przez proxy jakiegoś znaczącego Komunikatu o błędzie)!

Robienie pełnego wyrażenia regularnego dla JSON jest niepotrzebne dlatego (jak by to było - z mojego doświadczenia-dla większości przypadków użycia). Prawdopodobnie lepiej byłoby użyć czegoś takiego jak poniżej:

function (someString) {
  // test string is opened with curly brace or machine bracket
  if (someString.trim().search(/^(\[|\{){1}/) > -1) {
    try { // it is, so now let's see if its valid JSON
      var myJson = JSON.parse(someString);
      // yep, we're working with valid JSON
    } catch (e) {
      // nope, we got what we thought was JSON, it isn't; let's handle it.
    }
  } else {
    // nope, we're working with non-json, no need to parse it fully
  }
}

To powinno oszczędzić Ci konieczności obsługi Exception handle valid non-JSON code i dbania o duff json w tym samym czasie.

 1
Author: Jay Edwards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 12:08:07
if(resp) {
    try {
        resp = $.parseJSON(resp);
        console.log(resp);
    } catch(e) {
        alert(e);
    }
}

Mam nadzieję, że to działa również dla ciebie

 1
Author: Darkcoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 08:53:06

Tutaj jest też wersja maszynopisu:

JSONTryParse(input) {
    try {
        //check if the string exists
        if (input) {
            var o = JSON.parse(input);

            //validate the result too
            if (o && o.constructor === Object) {
                return o;
            }
        }
    }
    catch (e) {
    }

    return false;
};
 0
Author: student,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-29 11:36:57

Oh możesz zdecydowanie użyć try catch, aby sprawdzić, czy jest to poprawny JSON

testowane na Firfox Quantom 60.0.1

Użyj funkcji wewnątrz funkcji, aby przetestować JSON i użyj tego wyjścia, aby zweryfikować łańcuch znaków. / align = "left" /

    function myfunction(text){

       //function for validating json string
        function testJSON(text){
            try{
                if (typeof text!=="string"){
                    return false;
                }else{
                    JSON.parse(text);
                    return true;                            
                }
            }
            catch (error){
                return false;
            }
        }

  //content of your real function   
        if(testJSON(text)){
            console.log("json");
        }else{
            console.log("not json");
        }
    }

//use it as a normal function
        myfunction('{"name":"kasun","age":10}')
 0
Author: Aylian Craspa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-01 10:01:23

Oto Mój kod roboczy:

function IsJsonString(str) {
try {
  var json = JSON.parse(str);
  return (typeof json === 'object');
} catch (e) {
  return false;
}
 -1
Author: Anand Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-11 06:06:44