forum

Home / DeveloperSection / Forums / Determine if single value or sub array JSON

Determine if single value or sub array JSON

Anonymous User249110-May-2013
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!


Updated on 10-May-2013
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By