如何检查 JavaScript 对象是否为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11182924/
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-24 04:49:04  来源:igfitidea点击:

How to check if JavaScript object is JSON

javascriptjson

提问by Wei Hao

I have a nested JSON object that I need to loop through, and the value of each key could be a String, JSON array or another JSON object. Depending on the type of object, I need to carry out different operations. Is there any way I can check the type of the object to see if it is a String, JSON object or JSON array?

我有一个需要循环遍历的嵌套 JSON 对象,每个键的值可以是字符串、JSON 数组或另一个 JSON 对象。根据对象的类型,我需要进行不同的操作。有什么方法可以检查对象的类型以查看它是字符串、JSON 对象还是 JSON 数组?

I tried using typeofand instanceofbut both didn't seem to work, as typeofwill return an object for both JSON object and array, and instanceofgives an error when I do obj instanceof JSON.

我尝试使用typeofandinstanceof但两者似乎都不起作用,因为typeof会为 JSON 对象和数组返回一个对象,并且instanceof在执行obj instanceof JSON.

To be more specific, after parsing the JSON into a JS object, is there any way I can check if it is a normal string, or an object with keys and values (from a JSON object), or an array (from a JSON array)?

更具体地说,在将 JSON 解析为 JS 对象后,有什么方法可以检查它是普通字符串,还是带有键和值的对象(来自 JSON 对象),或数组(来自 JSON 数组) )?

For example:

例如:

JSON

JSON

var data = "{'hi':
             {'hello':
               ['hi1','hi2']
             },
            'hey':'words'
           }";

Sample JavaScript

示例 JavaScript

var jsonObj = JSON.parse(data);
var path = ["hi","hello"];

function check(jsonObj, path) {
    var parent = jsonObj;
    for (var i = 0; i < path.length-1; i++) {
        var key = path[i];
        if (parent != undefined) {
            parent = parent[key];
        }
    }
    if (parent != undefined) {
        var endLength = path.length - 1;
        var child = parent[path[endLength]];
        //if child is a string, add some text
        //if child is an object, edit the key/value
        //if child is an array, add a new element
        //if child does not exist, add a new key/value
    }
}

How do I carry out the object checking as shown above?

如何进行如上所示的对象检查?

回答by Peter Wilkinson

I'd check the constructor attribute.

我会检查构造函数属性。

e.g.

例如

var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.

编辑:添加了空检查和未定义的检查。

回答by McGarnagle

You can use Array.isArrayto check for arrays. Then typeof obj == 'string', and typeof obj == 'object'.

您可以使用Array.isArray来检查数组。然后typeof obj == 'string'typeof obj == 'object'

var s = 'a string', a = [], o = {}, i = 5;
function getType(p) {
    if (Array.isArray(p)) return 'array';
    else if (typeof p == 'string') return 'string';
    else if (p != null && typeof p == 'object') return 'object';
    else return 'other';
}
console.log("'s' is " + getType(s));
console.log("'a' is " + getType(a));
console.log("'o' is " + getType(o));
console.log("'i' is " + getType(i));

's' is string
'a' is array
'o' is object
'i' is other

's' 是字符串
'a' 是数组
'o' 是对象
'i' 是其他

回答by Martin Wantke

An JSON object isan object. To check whether a type is an object type, evaluate the constructor property.

JSON 对象一个对象。要检查类型是否为对象类型,请评估构造函数属性。

function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}

The same applies to all other types:

这同样适用于所有其他类型:

function isArray(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Array;
}

function isBoolean(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Boolean;
}

function isFunction(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Function;
}

function isNumber(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Number;
}

function isString(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == String;
}

function isInstanced(obj)
{
    if(obj === undefined || obj === null) { return false; }

    if(isArray(obj)) { return false; }
    if(isBoolean(obj)) { return false; }
    if(isFunction(obj)) { return false; }
    if(isNumber(obj)) { return false; }
    if(isObject(obj)) { return false; }
    if(isString(obj)) { return false; }

    return true;
}

回答by JoshRagem

If you are trying to check the type of an objectafter you parse a JSONstring, I suggest checking the constructor attribute:

如果您object在解析JSON字符串后尝试检查 an 的类型,我建议检查构造函数属性:

obj.constructor == Array || obj.constructor == String || obj.constructor == Object

This will be a much faster check than typeof or instanceof.

这将是比 typeof 或 instanceof 快得多的检查。

If a JSON librarydoes not return objects constructed with these functions, I would be very suspiciouse of it.

如果JSON 库不返回用这些函数构造的对象,我会非常怀疑它。

回答by Dmitry Efimenko

The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof

@PeterWilkinson 的答案对我不起作用,因为“类型化”对象的构造函数是根据该对象的名称自定义的。我不得不使用typeof

function isJson(obj) {
    var t = typeof obj;
    return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}

回答by matt3141

You could make your own constructor for JSON parsing:

您可以为 JSON 解析创建自己的构造函数:

var JSONObj = function(obj) { $.extend(this, JSON.parse(obj)); }
var test = new JSONObj('{"a": "apple"}');
//{a: "apple"}

Then check instanceof to see if it needed parsing originally

然后检查 instanceof 看它是否需要最初解析

test instanceof JSONObj

回答by Dawson B

I wrote an npm module to solve this problem. It's available here:

我写了一个 npm 模块来解决这个问题。它可以在这里找到

object-types: a module for finding what literal types underly objects

object-types: 用于查找对象下的文字类型的模块

Install

安装

  npm install --save object-types



Usage

用法

const objectTypes = require('object-types');

objectTypes({});
//=> 'object'

objectTypes([]);
//=> 'array'

objectTypes(new Object(true));
//=> 'boolean'

Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types

看一看,它应该可以解决您的确切问题。如果您有任何问题,请告诉我!https://github.com/dawsonbotsford/object-types

回答by Martin Skorupski

I combine the typeof operator with a check of the constructor attribute (by Peter):

我将 typeof 运算符与构造函数属性的检查结合起来(由 Peter):

var typeOf = function(object) {
    var firstShot = typeof object;
    if (firstShot !== 'object') {
        return firstShot;
    } 
    else if (object.constructor === [].constructor) {
        return 'array';
    }
    else if (object.constructor === {}.constructor) {
        return 'object';
    }
    else if (object === null) {
        return 'null';
    }
    else {
        return 'don\'t know';
    } 
}

// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];

console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));
testSubjects.map(function(testSubject){
    console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));
});

Result:

结果:

typeOf()    input parameter
---------------------------
boolean     true
boolean     false
number      1
number      2.3
string      "string"
array       [4,5,6]
object      {"foo":"bar"}
null        null
undefined       

回答by arielhad

you can also try to parse the data and then check if you got object:

您也可以尝试解析数据,然后检查是否有对象:

var testIfJson = JSON.parse(data);
if (typeOf testIfJson == "object")
{
//Json
}
else
{
//Not Json
}

回答by Sandro Rosa

Try this

尝试这个

if ( typeof is_json != "function" )
function is_json( _obj )
{
    var _has_keys = 0 ;
    for( var _pr in _obj )
    {
        if ( _obj.hasOwnProperty( _pr ) && !( /^\d+$/.test( _pr ) ) )
        {
           _has_keys = 1 ;
           break ;
        }
    }

    return ( _has_keys && _obj.constructor == Object && _obj.constructor != Array ) ? 1 : 0 ;
}

It works for the example below

它适用于下面的示例

var _a = { "name" : "me",
       "surname" : "I",
       "nickname" : {
                      "first" : "wow",
                      "second" : "super",
                      "morelevel" : {
                                      "3level1" : 1,
                                      "3level2" : 2,
                                      "3level3" : 3
                                    }
                    }
     } ;

var _b = [ "name", "surname", "nickname" ] ;
var _c = "abcdefg" ;

console.log( is_json( _a ) );
console.log( is_json( _b ) );
console.log( is_json( _c ) );