views:

108

answers:

4

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.

+3  A: 

Use a JSON parser like JSON.parse:

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
Gumbo
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
Get it at http://json.org/json2.js. It does not use try / catch. You can modify the code to replace the throw statements.
Mark Lutton
Good call Mark! json2.js is free to copy and modify too!
Chi Chan
+2  A: 

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();
Ifi
Thanks, but I think using the prototype library to do this is a little overkilled.
Chi Chan
+2  A: 

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.

The Elite Gentleman
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
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
@Mark Lutton, the object type won't be of JSON but of XML Dom Document (I forgot what the exact type in firefox is).
The Elite Gentleman
@Chi Chan. You can use option 2 without using try/catch. Without using try/catch you basically allowing harm to come to your program.
The Elite Gentleman
eval also accepts valid JavaScript, like "alert(5);" and strings in single quotes, which are not valid JSON.
Mark Lutton
Hey Gentleman :), What I wanted isn't just the without using the try/catch block. That will throw an error and we don't want THAT. What I meant was checking for the string without doing a try/catch. Some of us have the debugger set to break on all exceptions (even if it's catched) and breaking everytime we get a non json string is not ideal.
Chi Chan
@Mark Lutton, I hope you read my warning sentence. I said that eval executes Javascript code so `alert(5)` is valid for eval. Check my updated post.
The Elite Gentleman
@Chi Chan, use JSON.org's `JSON.parse` instead. My 2nd example shows just that.
The Elite Gentleman
Hey Gentleman, Yup, that's what I ended up using with a little modification to the code. JSON.parse will throw "SyntaxError('JSON.parse');" for an invalid json string, hence I added a little modification to it.
Chi Chan
A: 

Have a look around the line 450 in http://www.json.org/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

}
Mic
Thanks Mic, This is what I ended up doing, except I left the "if (cx.test(text))" before the regexp check.
Chi Chan