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

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

    You can use the javascript eval() function to verify if it's valid.

    e.g.

    var jsonString = '{ "Id": 1, "Name": "Coke" }';
    var json;
    
    try {
      json = eval(jsonString);
    } catch (exception) {
      //It's advisable to always catch an exception since eval() is a javascript executor...
      json = null;
    }
    
    if (json) {
      //this is json
    }
    

    Alternatively, you can use JSON.parse function from json.org:

    try {
      json = JSON.parse(jsonString);
    } catch (exception) {
      json = null;
    }
    
    if (json) {
      //this is json
    }
    

    Hope this helps.

    WARNING: eval() is dangerous if someone adds malicious JS code, since it will execute it. Make sure the JSON String is trustworthy, i.e. you got it from a trusted source.

    Edit For my 1st solution, it's recommended to do this.

     try {
          json = eval("{" + jsonString + "}");
        } catch (exception) {
          //It's advisable to always catch an exception since eval() is a javascript executor...
          json = null;
        }
    

    To guarantee json-ness. If the jsonString isn't pure JSON, the eval will throw an exception.

提交回复
热议问题