boom
boom

Reputation: 11686

How to detect when json isn't json (it's html)

I'm working with a companies broken API. When the endpoint isn't available I don't hit an error it just sends back page unavailable HTML in the body (normally it returns JSON).

I'm trying to figure out how to detect if the body should be parsed into json or thrown out.

I'm using javascript, any help is appreciated.

Upvotes: 0

Views: 89

Answers (1)

Kenneth
Kenneth

Reputation: 28737

You could just try to parse it and if it fails, it's not valid JSON:

function tryParse(jsonstring){
    try{
       return JSON.parse(jsonstring);
    }
    catch(err){
       return null;
    }
}

Upvotes: 5

Related Questions