简体   繁体   中英

Determine if single value or sub array JSON

I have an algorithm which binds an object from MVC (C#) to the view. The key and the data can be anything, this is up to the implementer.

The issue that I am having is that I cannot determine if something in the JSON string is an array or a simple string. The following code works recursively. If it is an array, it needs to dig deeper. Otherwise, it will bind the value it found based on the key and value.

function constructView(data)
{
    for(var key in data)
    {
        if (data[key].length > 1)
        {
            var count = 0;

            while (count < data.length)
            {
                constructView(data[count]);
                count++;
            }
        }
        $("#" + key).html(data[key]);
    }
}

This is just a prototype, so at the moment it does not generate components but simply does bindings.

Ok, so, the issue:

When I pass in

{"data":"this is a response","strings":["test1","test2"]}

it returns 18 and 2 for lengths. This is because both are technically arrays with a valid length.

Is there a way to get a item length? Where it considers a lone string as 1 item and the array as its respective item count?

I can verify that the JSON array is passed in properly.

Any help is greatly appreciated!

Array.isArray(x)

will check for an array, although you'll need a polyfill (pretty easy to find) if you need to support legacy browsers.

typeof x === "string"

will indicate a string

On modern, ES5 compatible implementations, there is Array.isArray :

var a = [];
Array.isArray(a); // true

On older implementations you need this ugly workaround:

function isArray(a) {
    return ({}).toString.call(a) === "[object Array]";
    // or: 
    // return Object.prototype.toString.call(a) === "[object Array]";
}

查看其他答案,但是如果您不想担心polyfill,您似乎已经在使用jQuery(继续使用$(...).html(...) ),那么为什么不使用jQuery的$.isArray()函数

由于您正在使用JQuery,因此可以使用:

if ($.type(data[key])==="array")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM