You can use the javascript eval() function to verify if it's valid.
e.g.
var jsonString = '{ "Id": 1, "Name": "Coke" }';
var json;
try {
json = eval(jsonString);
} catch (exception) {
//It's advisable to always catch an exception since eval() is a javascript executor...
json = null;
}
if (json) {
//this is json
}
Alternatively, you can use JSON.parse
function from json.org:
try {
json = JSON.parse(jsonString);
} catch (exception) {
json = null;
}
if (json) {
//this is json
}
Hope this helps.
WARNING eval() is Dangerous if someone adds malicious JS code, since it will execute it. Make sure the JSON String is trustworthy, i.e. you got it from a trusted source.
Edit For my 1st solution, it's recommended to do this.
try {
json = eval("{" + jsonString + "}");
} catch (exception) {
//It's advisable to always catch an exception since eval() is a javascript executor...
json = null;
}
To guarantee json-ness. If the jsonString
isn't pure JSON, the eval will throw an exception.