你怎么知道javascript中的对象是否是JSON? [英] How do you know if an object is JSON in javascript?

查看:54
本文介绍了你怎么知道javascript中的对象是否是JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.).

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

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

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

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

所以是的......我推荐使用try / catch方法。 ; - )

So yeah… I'd recommend the try/catch approach. ;-)

这篇关于你怎么知道javascript中的对象是否是JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆