Jam*_*ead 14 javascript jquery json
我怎么知道变量是JSON还是其他东西?是否有一个JQuery函数或我可以用来解决这个问题的东西?
Ben*_*ank 15
根据您的评论,听起来您不想知道字符串是否是有效的JSON,而是一个对象是否可以成功编码为JSON(例如,不包含任何Date对象,用户定义的类的实例,等等.).
这里有两种方法:尝试分析对象及其"子"(注意递归对象)或者吮吸它.如果你手头有一个JSON编码器(JSON.stringify在最近的浏览器或jquery-json这样的插件中),后者可能是更简单,更强大的方法:
function canJSON(value) {
try {
JSON.stringify(value);
return true;
} catch (ex) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
直接分析对象需要您能够判断它是否是"普通"对象(即使用对象文字或对象创建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;
}
Run Code Online (Sandbox Code Playgroud)
所以是的...我建议使用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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Douglas Crockfords JSON Github 站点中的 [json2.js]来解析它。