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

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

    I know i'm 3 years late to this question, but I felt like chiming in.

    While Gumbo's solution works great, it doesn't handle a few cases where no exception is raised for JSON.parse({something that isn't JSON})

    I also prefer to return the parsed JSON at the same time, so the calling code doesn't have to call JSON.parse(jsonString) a second time.

    This seems to work well for my needs:

    function tryParseJSON (jsonString){
        try {
            var o = JSON.parse(jsonString);
    
            // Handle non-exception-throwing cases:
            // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
            // but... JSON.parse(null) returns null, and typeof null === "object", 
            // so we must check for that, too. Thankfully, null is falsey, so this suffices:
            if (o && typeof o === "object") {
                return o;
            }
        }
        catch (e) { }
    
        return false;
    };
    

提交回复
热议问题