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

前端 未结 24 2126
暖寄归人
暖寄归人 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

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

提交回复
热议问题