0

i have this json data and i want to get length of this json data and also of css

my json data is shown here

jso({tag:"div",css:{backgroundColor:"red"},html:"abc"})

i have pass this in function

 function jso(data){
    alert(data.length)
}

3 Answers3

1

Your JSON is not a valid JSON object

{
  "tag": "div",
  "css": {
     "backgroundColor":"red"
  },
  "html":"abc"
}

However proper JSON object don't have a length attribute, so you need to iterate over them to calculate the length.

GillesC
  • 10,647
  • 3
  • 40
  • 55
1

i know what u mean u just need to loop over your object with a counter variable

var x = {tag:"div",css:{backgroundColor:"red"},html:"abc"}

function objectLength(obj){

var counter = 0;

for(var i in obj)
{
counter +=1;
}
return counter
}

use it like this

alert(objectLength(x))
Marwan
  • 2,362
  • 1
  • 20
  • 35
0

To iterate over the data using jQuery counting how many iterations you did do the following:

var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};

var count = 0;
$.each(data, function(key, value) {
    count++;
});

See jsFiddle here.

To iterate over the data using JavaScript only counting how many iterations you did do the following:

var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};

var count = 0;
var key;
for(key in data)
{
    var value = data[key];
    count++;
}

​See jsFiddle here.

scottheckel
  • 9,106
  • 1
  • 35
  • 47