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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2481614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:33:18  来源:igfitidea点击:

How do you know if an object is JSON in javascript?

javascriptjqueryjson

提问by James Armstead

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 还是其他变量?有没有 JQuery 函数或我可以用来解决这个问题的东西?

回答by Ben Blank

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(例如,不包含任何 Date 对象、用户定义的类的实例、等等。)。

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.stringifyin recent browsers or a plugin such as jquery-json), the latter is probably the simpler and more robust approach:

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

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

直接分析一个对象要求您能够判断它是否是“普通”对象(即使用对象字面量或创建的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;
}

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

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

回答by mts7

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

回答by Ignacio Vazquez-Abrams

You can use [json2.js] from Douglas Crockfords JSON Github siteto parse it.

您可以使用Douglas Crockfords JSON Github 站点中的[json2.js]来解析它。

回答by PP.

JSON is an encoding method not an internal variable type.

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

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.

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

回答by aakoch

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

我所做的唯一测试是检查一个带双引号和不带双引号的字符串,这通过了该测试。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

编辑:看起来最新的 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);

}

}