Determine if single value or sub array JSON

Total Post:183


 1967  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)
        $("#" + 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!

  1. Re: Determine if single value or sub array JSON

    Hi Ankita!


    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


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.