Ash
Ash

Reputation: 237

Getting the lengh of an JSON array

I am having a json file. I can get the data in the json file using

$.getJSON.json("mock/Insight72.json", function (jsondata) {
    response = jsondata.Data1;
    response2 = jsondata.Data2;
});

But I want to find the length of the Data1 and Data2. What should I do?

Here`s the JSON data(Only the Fruit Part)..

],
"Data1": {
    "kitchen selectives": [{
        "displayColor": "#DC143C",
            "numProducts": 1,
            "averagePrice": 25.99,
    }],
        "aroma": [{
        "displayColor": "#991F1F",
            "numProducts": 1,
            "averagePrice": 60.25,
    }, {
        "displayColor": "#DC143C",
            "numProducts": 1,
            "averagePrice": 46.19,
    }, ............

Upvotes: 0

Views: 167

Answers (3)

martin jrk
martin jrk

Reputation: 185

You can use two different approaches

  1. This one is not compatible with IE7 and 8. Look here as well.

    var length = Object.keys(response).length;
    var length2 = Object.keys(response2).length;
    
  2. This one will itterate through json and return length:

    function getJSONLegth(response) {
        var count = 0;
        for (var k in response) {
            count++;
        }
        return count;
    }    
    
    var length = getJSONLegth(response);
    var length2 = getJSONLegth(response2);
    

    Did it help you?

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

As Data1 appears to be an Object ({...}), it'll only have a length if one was explicitly given as another key/value:

{
    "aroma": [],
    "length": 2
}

However, if you'd like to know the number of keys/properties it has, you can use Object.keys():

var keyCountData1 = Object.keys(jsondata.Data1).length;

You can also retrieve the length of any Array ([...]) within Data1, such as "aroma":

var aromas = jsondata.Data1.aroma.length;

Or, if you want to know the length of the Object as JSON:

var dataLength = JSON.stringify(jsondata.Data1).length;

Beyond that, however, you'll have to clarify exactly what "length" you're hoping for.

Upvotes: 3

rid
rid

Reputation: 63472

To find out how many elements are in the response object, you can do something like:

var length = 0;
for (var key in response) {
    response.hasOwnProperty(key) && ++length;
}

If you want to find out the total length of all the arrays under it, you can do something like:

var length = 0;
for (var key in response) {
    response.hasOwnProperty(key) && length += response[key].length;
}

Upvotes: 2

Related Questions