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

前端 未结 24 1786
暖寄归人
暖寄归人 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: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}')
    

提交回复
热议问题