How to check if a string is a valid JSON string in JavaScript without using Try/Catch

前端 未结 24 2099
暖寄归人
暖寄归人 2020-11-22 07:50

Something like:

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

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString(\"foo\");         


        
24条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 08:29

    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);
      }
    

    so this is the version that can be used passing a string object

    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 }" ) )

提交回复
热议问题