im new to json. Ive created objects similar in structure to the attached json string. I believe what ive created, intentionally, is a nested array object...
{
"tracelog":{
"title":"",
"phase":"12",
"users":"",
"logduration":"",
"logdurationtype":"undefined",
"showlogduedate":"no",
"durationstartfield":"",
"fields":[
{
"atts":[
{
"name":"dfvdfv",
"fieldtype":"text",
"followedbydate":"no",
"datetype":"---",
"fieldduration":"---",
"fielddurationtype":"undefined",
"fielddurationstart":"",
"autocalcunits":"none",
"validationtype":"none",
"fieldvisibleto":"",
"fieldaccessibleto":"",
"dropdown":""
}
]
},
{
"atts":[
{
"name":"ffff",
"fieldtype":"text",
"followedbydate":"no",
"datetype":"---",
"fieldduration":"---",
"fielddurationtype":"undefined",
"fielddurationstart":"",
"autocalcunits":"none",
"validationtype":"none",
"fieldvisibleto":"",
"fieldaccessibleto":"",
"dropdown":""
}
]
}
]
}
}
What i want to do is find the length of the array named "atts". Ive parsed the JSON string as follows...
var obj = jQuery.parseJSON(jsonstring);
... and later call the objects thusly ...
obj.tracelog.fields.length
accurately tells me how many fields there are.
obj.tracelog.fields[0].atts.name
... gives me the name, but throws a console error saying field[0] is undefined. so it works, and it doesnt. while ....
obj.tracelog.fields[0].atts.length
does NOT give me the number of fields in the "atts" array (if it is infact an array - id like it to be) but gives me "undefined".
Can someone point out where im going wrong here?
thanks.
1 Answer 1
obj.tracelog.fields[0].atts
is an array so you must access it like so:
obj.tracelog.fields[0].atts[0].name
Addressing the latter part of your question:
obj.tracelog.fields[0].atts.length
does give you the number of items in the array, which in your example is one object. It seems what you actually want to do is count the number of properties on the first object in that array (i.e., obj.tracelog.fields[0].atts[0]
). There is no simple .length
style property that will give you the number of properties on an object, but you can loop over them and count like this:
var count = 0;
for (var test in obj.tracelog.fields[0].atts[0]) {
count++;
}
alert(count);
6 Comments
Object.keys(your_object).length
is also a nice one liner, even if less efficient.obj.tracelog.fields[0].atts.length
should return 1 because it is an array with one object in it. What you want to do is count the number of properties on obj.tracelog.fields[0].atts[0]
object which I've provided in my example above.
obj.tracelog.fields[0].atts
is actually an array. So this could not have worked:obj.tracelog.fields[0].atts.name
. It wouldn't have errored out, but it should have returnedundefined
, not the name. You would have needed to use:obj.tracelog.fields[0].atts[0].name
Object.keys(obj.tracelog.fields[0].atts[0]).length
in ES5 compliant hosts.