How do I know if a variable is JSON or if it is something else? Is there a JQuery function or something I can use to figure this out?
5 Answers
Based on your comments, it sounds like you don't want to know whether a string is valid JSON, but rather whether an object could be successfully encoded as JSON (e.g. doesn't contain any Date objects, instances of user-defined classes, etc.).
There are two approaches here: try to analyze the object and its "children" (watch out for recursive objects) or suck-it-and-see. If you have a JSON encoder on hand (JSON.stringify
in recent browsers or a plugin such as jquery-json), the latter is probably the simpler and more robust approach:
function canJSON(value) {
try {
JSON.stringify(value);
return true;
} catch (ex) {
return false;
}
}
Analyzing an object directly requires that you be able to tell whether it is a "plain" object (i.e. created using an object literal or new Object()
), which in turn requires you be able to get its prototype, which isn't always straightforward. I've found the following code to work in IE7, FF3, Opera 10, Safari 4, and Chrome (and quite likely other versions of those browsers, which I simply haven't tested).
var getPrototypeOf;
if (Object.getPrototypeOf) {
getPrototypeOf = Object.getPrototypeOf;
} else if (typeof ({}).__proto__ === "object") {
getPrototypeOf = function(object) {
return object.__proto__;
}
} else {
getPrototypeOf = function(object) {
var constructor = object.constructor;
if (Object.prototype.hasOwnProperty.call(object, "constructor")) {
var oldConstructor = constructor; // save modified value
if (!(delete object.constructor)) { // attempt to "unmask" real constructor
return null; // no mask
}
constructor = object.constructor; // obtain reference to real constructor
object.constructor = oldConstructor; // restore modified value
}
return constructor ? constructor.prototype : null;
}
}
// jQuery.isPlainObject() returns false in IE for (new Object())
function isPlainObject(value) {
if (typeof value !== "object" || value === null) {
return false;
}
var proto = getPrototypeOf(value);
// the prototype of simple objects is an object whose prototype is null
return proto !== null && getPrototypeOf(proto) === null;
}
var serializablePrimitives = { "boolean" : true, "number" : true, "string" : true }
function isSerializable(value) {
if (serializablePrimitives[typeof value] || value === null) {
return true;
}
if (value instanceof Array) {
var length = value.length;
for (var i = 0; i < length; i++) {
if (!isSerializable(value[i])) {
return false;
}
}
return true;
}
if (isPlainObject(value)) {
for (var key in value) {
if (!isSerializable(value[key])) {
return false;
}
}
return true;
}
return false;
}
So yeah… I'd recommend the try/catch approach. ;-)

- 54,908
- 28
- 127
- 156
-
1Interresting. The way I read his question, he seems to look for an "isJSON" function, the exact opposite of what you understood from his question. – ychaouche Nov 13 '12 at 09:23
-
@ychaouche — Yes, I found the question to be quite ambiguous. However, James' comment on [Ignacio's answer](http://stackoverflow.com/a/2481623/46387) mentions "pass[ing] `var json = {"test":"test"}` to it", which I took to mean that he wanted to feed in an object. As he never accepted an answer, I doubt we'll ever be sure what he wanted. :-) – Ben Blank Nov 13 '12 at 16:56
function isJSON(data) {
var isJson = false
try {
// this works with JSON string and JSON object, not sure about others
var json = $.parseJSON(data);
isJson = typeof json === 'object' ;
} catch (ex) {
console.error('data is not JSON');
}
return isJson;
}

- 583
- 4
- 12
-
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 an example string: `{ "Id": 1, "Name": "Coke" }`. It returns `false` for me. – trejder Sep 29 '12 at 09:18
You can use [json2.js] from Douglas Crockfords JSON Github site to parse it.

- 15,342
- 16
- 114
- 137

- 776,304
- 153
- 1,341
- 1,358
-
1This nearly worked... If you pass var json = {"test":"test"} to it.. it wont work.. so if you do a stringify on it.. it will pass that validation, but if you pass a normal string ("asdf") to it.. it won't throw an error?! – James Armstead Mar 20 '10 at 02:52
-
2I think the idea is to have it pass isJSON before sending it to json2.js's JSON.parse. – aakoch Oct 13 '10 at 15:17
JSON is an encoding method not an internal variable type.
You might load in some text that is JSON encoded that javascript then uses to populate your variables. Or you might export a string that contains a JSON encoded dataset.

- 10,764
- 7
- 45
- 59
The only testing I've done is to check for a string, with and without double quotes, and this passes that test. http://forum.jquery.com/topic/isjson-str
Edit: It looks like the latest Prototype has a new implementation similar to the one linked above. http://prototypejs.org/assets/2010/10/12/prototype.js
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}

- 1,164
- 1
- 9
- 18
-
1-1: There is no chance, you can use this function in pure JavaScript! There is no such function like `blank()` defined for `String`. And I have no idea, how would you like to use object-oriented approach (`var str = this`) on non-object function definition? – trejder Sep 29 '12 at 09:28
-
Good catch! 1) The .blank() came from Prototype - they extended String to include this. 2) The function assumes you're doing a similar thing and the function is part of an object. – aakoch Oct 24 '12 at 14:57