Home > DeveloperSection > Forums > Determine if single value or sub array JSON
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    May-10-2013 3:57 AM

 JSON JSON 
Ratings:


 1 Reply(s)
 1096  View(s)
Rate this:
Hi Expert!

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!
Thanks in advance!



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-10-2013 9:19 AM

Hi Ankita!

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

Don't want to miss updates? Please click the below button!

Follow MindStick