Something like:

var jsonString = '{ "Id": 1, "Name": "Coke" }';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")

EDIT: The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid Json strings.

share|improve this question
feedback

5 Answers

up vote 28 down vote accepted

Use a JSON parser like JSON.parse:

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
share|improve this answer
Thank you, but I just ran this with the team and they want something that doesn't use try/catch. The question is edited along with a new title. Sorry about that. – Chi Chan Sep 14 '10 at 15:26
1  
Get it at json.org/json2.js. It does not use try / catch. You can modify the code to replace the throw statements. – Mark Lutton Sep 14 '10 at 15:27
Good call Mark! json2.js is free to copy and modify too! – Chi Chan Sep 14 '10 at 15:47
Hm... Strange... I used this example and it works fine for me (JSON object from PHP's json_encode passes as valid), but it doesn't work for the example in question: { "Id": 1, "Name": "Coke" }. It returns false for me. – trejder Sep 29 '12 at 9:16
feedback

Maybe it will useful:

    function parseJson(code)
{
    try {
        return JSON.parse(code);
    } catch (e) {
        return code;
    }
}
function parseJsonJQ(code)
{
    try {
        return $.parseJSON(code);
    } catch (e) {
        return code;
    }
}

var str =  "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
alert(typeof parseJson(str));
alert(typeof parseJsonJQ(str));
var str_b  = "c";
alert(typeof parseJson(str_b));
alert(typeof parseJsonJQ(str_b));

output:

IE7: string,object,string,string

CHROME: object,object,string,string

share|improve this answer
feedback

Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js

There is a regexp that check for a valid JSON, something like:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

  //the json is ok

}else{

  //the json is not ok

}
share|improve this answer
Thanks Mic, This is what I ended up doing, except I left the "if (cx.test(text))" before the regexp check. – Chi Chan Sep 14 '10 at 15:55
2  
This is only checking if the code is safe for eval to use. For example the following string '2011-6-27' would pass that test. – SystemicPlural Jul 27 '11 at 16:22
feedback

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.

share|improve this answer
First example using eval says that "<div>foo</div>" is valid JSON. It may work differently in different browsers, but it appears that in FireFox, eval() accepts XML. – Mark Lutton Sep 14 '10 at 15:26
Thank you, but I just ran this with the team and they want something that doesn't use try/catch. The question is edited along with a new title. Sorry about that. – Chi Chan Sep 14 '10 at 15:26
@Mark Lutton, the object type won't be of JSON but of XML Dom Document (I forgot what the exact type in firefox is). – Buhake Sindi Sep 14 '10 at 15:30
@Chi Chan. You can use option 2 without using try/catch. Without using try/catch you basically allowing harm to come to your program. – Buhake Sindi Sep 14 '10 at 15:32
eval also accepts valid JavaScript, like "alert(5);" and strings in single quotes, which are not valid JSON. – Mark Lutton Sep 14 '10 at 15:48
show 4 more comments
feedback

in prototype js we have method isJSON. try that

http://api.prototypejs.org/language/string/prototype/isjson/

even http://www.prototypejs.org/learn/json

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
share|improve this answer
3  
Thanks, but I think using the prototype library to do this is a little overkilled. – Chi Chan Sep 14 '10 at 15:29
1  
You gave FOUR examples but only THREE results. What is the result for "{ foo: 42 }".isJSON()? If false, as I assume (result should follow function it document), then good question is, why it is false? { foo: 42 } seems to be perfectly valid JSON. – trejder Sep 29 '12 at 9:58
1  
@trejder Unfortunately, the JSON spec requires quoted keys. – mikermcneil Oct 8 '12 at 1:27
And "2002-12-15".isJSON returns true, while JSON.parse("2002-12-15") throws an error. – ychaouche Nov 13 '12 at 17:14
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.