如何检查JavaScript对象是否为JSON

Wei*_*Hao 71 javascript json

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

我尝试使用typeof,instanceof但两者似乎都没有工作,因为typeof它将为JSON对象和数组返回一个对象,并instanceof在我这样做时给出错误obj instanceof JSON.

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

例如:

JSON

var data = "{'hi':
             {'hello':
               ['hi1','hi2']
             },
            'hey':'words'
           }";
Run Code Online (Sandbox Code Playgroud)

示例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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*son 106

我检查构造函数属性.

例如

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]));
}
Run Code Online (Sandbox Code Playgroud)

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

  • `否则如果`是不必要的 (7认同)
  • 这么多“if”语句...使用[`switch`](https://www.w3schools.com/js/js_switch.asp)! (2认同)

McG*_*gle 18

您可以使用Array.isArray检查数组.然后键入obj =='string',并输入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));
Run Code Online (Sandbox Code Playgroud)

's'是字符串
'a'是数组
'o'是对象
'我'是另一个

  • 不要忘记考虑`typeof null ==='object'` (3认同)

ari*_*had 10

您还可以尝试解析数据,然后检查是否获得对象:

try {
    var testIfJson = JSON.parse(data);
    if (typeof testIfJson == "object"){
        //Json
    } else {
        //Not Json
    }
}
catch {
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果数据不可解析 JSON,这可能会导致“未捕获的语法错误” (2认同)

Mar*_*tke 10

JSON对象一个对象.要检查天气,任何类型都是对象类型,请评估构造函数属性.

function isObject(obj)
{
    return obj !== undefined && obj !== null && obj.constructor == Object;
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

  • JSON 编码的资源不是对象。它是一个字符串。只有在解码它或在 Javascript `JSON.parse()` 中,JSON 资源才会变成一个对象。因此,如果您测试来自服务器的资源以查看它是否是 JSON,最好首先检查 String,然后检查是否不是“&lt;empty string&gt;”,然后在解析之后检查它是否是对象。 (3认同)

Jos*_*gem 6

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

obj.constructor == Array || obj.constructor == String || obj.constructor == Object
Run Code Online (Sandbox Code Playgroud)

这将是比typeof或instanceof更快的检查.

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


mat*_*141 5

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

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

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

test instanceof JSONObj
Run Code Online (Sandbox Code Playgroud)


Dmi*_*try 5

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

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