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

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

    Very Simple one-liner code ( But Hacky approach )

    if (expected_json.id === undefined){
       // not a json
    }
    else{
       // json
    }
    

    NOTE: This only works if you are expecting something is JSON string like id. I am using it for an API and expecting the result either in JSON or some error string.

提交回复
热议问题