Reputation: 4523
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
Reputation: 15699
Use JSON.parse()
to check it.
Try:
try
{
var json = JSON.parse(your string);
}
catch(e)
{
//not a json
}
Upvotes: 3
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