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

前端 未结 24 2085
暖寄归人
暖寄归人 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: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. :)

提交回复
热议问题