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

前端 未结 24 1781
暖寄归人
暖寄归人 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 }" ) )

    0 讨论(0)
  • 2020-11-22 08:30

    I used a really simple method to check a string how it's a valid JSON or not.

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

    Result with a valid JSON string:

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

    Result with a simple string;

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

    Result with an object:

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

    Result with null input:

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

    The last one returns false because the type of null variables is object.

    This works everytime. :)

    0 讨论(0)
  • 2020-11-22 08:31

    Here is the typescript version too:

    JSONTryParse(input: any) {
        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: any) {
        }
    
        return false;
    };
    
    0 讨论(0)
  • 2020-11-22 08:31

    Oh you can definitely use try catch to check whether its or not a valid JSON

    Tested on Firfox Quantom 60.0.1

    use function inside a function to get the JSON tested and use that output to validate the string. hears an example.

        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 讨论(0)
  • 2020-11-22 08:34

    In prototypeJS, we have method isJSON. You can try that. Even json might help.

    "something".isJSON();
    // -> false
    "\"something\"".isJSON();
    // -> true
    "{ foo: 42 }".isJSON();
    // -> false
    "{ \"foo\": 42 }".isJSON();
    
    0 讨论(0)
  • 2020-11-22 08:35

    I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:

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

    So you may also dirty clip to the JSON object, like:

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

    As this as encapsuled as possible, it may not break on error.

    0 讨论(0)
提交回复
热议问题