Hassan Sardar
Hassan Sardar

Reputation: 4523

How to put a check on Jquery Data that either the data is in form of JSON or a simple HTML?

I want to check for the JSON Data.

That if I got a Data in form of JSON

Do this code

Else

This Code.

How can i do this ?

Example Variable for Data in Jquery:

data

Upvotes: 1

Views: 40

Answers (2)

codingrose
codingrose

Reputation: 15699

Use JSON.parse() to check it. Try:

try
{
   var json = JSON.parse(your string);
}
catch(e)
{
   //not a json
}

Fiddle here.

Upvotes: 3

Ashraf Bashir
Ashraf Bashir

Reputation: 9804

add this function to your code:

function isJSON(data) {
    try {
        JSON.parse(data);
        return true;
    } catch (ex) {
        return false;
    }
}

and simply to use it :

if(isJSON(data))
    // it's json, do whatever you want
else
    // it's not json, do whatever you want

Upvotes: 0

Related Questions