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

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

Something like:

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

//should be true
IsJsonString(jsonString);

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


        
24条回答
  •  萌比男神i
    2020-11-22 08:36

    This answer to reduce the cost of trycatch statement.

    I used JQuery to parse JSON strings and I used trycatch statement to handle exceptions, but throwing exceptions for un-parsable strings slowed down my code, so I used simple Regex to check the string if it is a possible JSON string or not without going feather by checking it's syntax, then I used the regular way by parsing the string using JQuery :

    if (typeof jsonData == 'string') {
        if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
            return jsonData;
        }
    }
    
    try {
        jsonData = $.parseJSON(jsonData);
    } catch (e) {
    
    }
    

    I wrapped the previous code in a recursive function to parse nested JSON responses.

提交回复
热议问题