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

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

    function get_json(txt)
    {  var data
    
       try     {  data = eval('('+txt+')'); }
       catch(e){  data = false;             }
    
       return data;
    }
    

    If there are errors, return false.

    If there are no errors, return json data

提交回复
热议问题