2

I have been working with JSON for quite a while now.

I know that JSON is stringified JavaScript Object.

I also know what makes JSON, as discussed in the below thread.

What is the difference between JSON and Object Literal Notation?

Question: But, I want to know if there is typeof kind of way that would tell me if a given string is JSON or just any other string.

What I have observed so far:

 1.   var data = {"name":"JS"};
      alert(typeof(data));  // object. Agree!


 2.  // I know this is JSON, by looking at the syntax
     var data = '{"name":"JS"}';
     alert(typeof(data));  // string. 

 3.  // I know this is just any other string (NOT JSON), by looking at the syntax.
     var data = "AnyOtherString";
     alert(typeof(data));  // string

Is there any way,in JavaScript, that I could differentiate between Point 2 & Point 3 above. Possibly, something similar to typeof that would tell me if its just a string or a JSON(also a string).?

Community
  • 1
  • 1
Sandeep Nayak
  • 4,649
  • 1
  • 22
  • 33
  • Try this question - http://stackoverflow.com/questions/10174898/how-to-check-whether-a-given-string-is-valid-json-in-java – LittlePanda Apr 24 '15 at 06:52
  • Also this might help - http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try – Sander Apr 24 '15 at 06:52

3 Answers3

8

To see if something is JSON: Try to parse it as JSON.

JSON.parse will throw an exception (which you can trap with try/catch) if it isn't.

function isJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (err) {
    return false;
  }
}

alert(
  isJSON('{"name":"JS"}') + " / " + isJSON("AnyOtherString")
);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

This may not be fast under large Strings, but is the only sure way:

function isJson(a){
  try {
        JSON.parse(response);
        return true;
    } catch(e) {
        return false;
    }
  }

If you are facing large strings, parsing them to JSON can be troublesome, then you could use basic validation, like searching for ':', '{', '}', which could reject some Strings on start, before entering real validation.

Here is some post that resolves it by regexp:

Community
  • 1
  • 1
Beri
  • 11,470
  • 4
  • 35
  • 57
2

No, JSON is just a string. The only thing you can do is to try to decode the string as JSON. If that succeeds, I suppose it was JSON. If not, it wasn't.

However, it seems worrisome that you need to guess in the first place. If you don't know what data you have, how can you productively work with it? Your application should have certain expectations of what data it holds at any moment and these expectations need to be met. Otherwise you can't write any reliable algorithm to work with that data. You should either know that you have JSON or that you don't.

deceze
  • 510,633
  • 85
  • 743
  • 889