i have json data looks this
{ "projects":{ "commercial":[ { "ppid":"87", "ptitle":"5th street lofts" }, { "ppid":"94", "ptitle":"skip-a-long child development services" } ], "corporate":[ { "ppid":"86", "ptitle":"caxton building" }, { "ppid":"68", "ptitle":"swiss valley corporate headquarters" } ], "education (collegiate)":[ { "ppid":"20", "ptitle":"ashford university - athletic field" }, { "ppid":"64", "ptitle":"st. ambrose university - center health , science education" } ] }, "error":"0" }
in example, "commercial", "corporate", , "education (collegiate)" unknown fields names.
i'm getting cgi, looks this:
$.ajax({ url: "cgi/mycgi.exe", datatype: "json", error: ajaxerror, success: function(json){ if(json.error !== "0"){ alert("error processing request: "+json.error); return; } var temp=""; var i=0; for(i=0;i<=json.projects.length-1;i++){ // tried } $.each(json.projects, function(ppid, ptitle) { // tried }); // add html } });
ultimately, want add html webpage, like
<div class="smsubtitle">commercial</div> <a href="somepage.html?id=87">fidlar technologies</a><br> <a href="somepage.html?id=94">skip-a-long child development services</a><br> <div class="smsubtitle">corporate</div>
etc.
i can't figure out how names of each project "sub title" it's individual field values.
edit: first, noticed json.projects.length undefined. tried json.projects[0].length undefined.
in
$.each(json.projects, function(ppid, ptitle) { console.log("test: "+ppid); console.log("test: "+ptitle); });
ppid works, ptitle says [object,object]
projects
property object , each object property contains array. have @ first iterate through object's keys , arrays, i.e. 2 nested loops:
var html = '', projects, type, i; ( type in json.projects ) { if ( json.projects.hasownproperty(type) ) { // append type of projects html += "<div class='smsubtitle'>" + type + "</div>"; projects = json.projects[type]; // iterate through each array ( = 0; < projects.length; i++ ) { html += "<a href='somepage.html?id="+ projects[i].ppid+ "'>"+ projects[i].ptitle +"</a><br>"; } } }