Saturday, 15 January 2011

jquery - Get JSON array name? -



jquery - Get JSON array name? -

let's assume have json file this:

{ "tools":[ { "category1":[ { "name":"sample name", "description":"sample desc", "version":"4.1" }, { "name":"another sample name", "description":"another sample desc", "version":"1.0" } ], "category2":[ { "name":"just sample name", "description":"description here", "version":"3.0-beta" } ] } ] }

now access file using $.getjson() method , for-loop in it. goal set every category name (category1, category2) <h1>-element, display contents of category. problem here don't know category names dynamically changed time time. i've tried far:

$.getjson('tools.json', function(data) { var output=""; (var in data.tools) { output+="<h1>" + data.tools[i] + "</h1>"; (var k in data.tools) { output+="data.tools[i][k].name - data.tools[i][k].desc - data.tools[i][k].version"; } }

this doesn't work because property name undefined. question how category name , access of content without knowing name of it?

thanks in advance.

try using object.keys()

var categories = object.keys(data.tools[0]); $.each(categories, function(index, category){ $('body').append('<h1>' + category + '</h1>'); var items = data.tools[0][category]; $.each(items, function(i, obj){ $('body').append(obj.name + '<br>'); }); });

here fiddle:

http://jsfiddle.net/mf99setb/

jquery json

No comments:

Post a Comment