你怎么知道javascript中的对象是否是JSON?

我怎么知道变量是JSON还是其他东西? 是否有一个JQuery函数或我可以用来解决这个问题的东西?

根据您的评论,听起来您不想知道字符串是否是有效的JSON,而是一个对象是否可以成功编码为JSON(例如,不包含任何Date对象,用户定义的类的实例,等等。)。

这里有两种方法:尝试分析对象及其“子”(注意递归对象)或者吮吸它。 如果您手头有JSON编码器(最近浏览器中的JSON.stringify或jquery-json等插件),后者可能是更简单,更强大的方法:

 function canJSON(value) { try { JSON.stringify(value); return true; } catch (ex) { return false; } } 

直接分析对象需要你能够判断它是否是一个“普通”对象(即使用对象文字或new Object() ),这反过来要求你能够获得它的原型,这并不总是直截了当。 我发现以下代码适用于IE7,FF3,Opera 10,Safari 4和Chrome(很可能是其他版本的浏览器,我根本没有测试过)。

 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; } 

所以是的...我建议使用try / catch方法。 😉

 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; } 

使用json2.js来解析它。

JSON是一种编码方法,而不是内部变量类型。

您可以加载一些JSON编码的文本,然后javascript将用于填充变量。 或者,您可以导出包含JSON编码数据集的字符串。

我做的唯一测试是检查一个字符串,有和没有双引号,这通过了该测试。 http://forum.jquery.com/topic/isjson-str

编辑:看起来最新的Prototype有一个类似于上面链接的新实现。 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); 

}