javascript - Recursive traversal of unknown json object/tree and actions based on returned json -
i'm using api returns json on request. json has either names next level url's or filename.
the problem code has recognize json returned.
if json has names next url levels create url , it. recursively new set of names or files, recognize , over. can go menu levels deep required. 1 *
if has filename should , render html. (this solved)
example of json
{id: 'new_url_1_level_1', id:'new_url_2_level_1', id:'new_url_3_level_1'} //or {id:'001200.file.ext',id:'001300.file.ext'...}
these turn http://my.api.call.com/new_url_1_level_1.../new_url1_level_2/...
the problem how loop on url's , filename example: http://my.api.call.com/new_url_1_level_1/new_url_1_level_2/new_url_1_level_3/001300.file.ext
my current script is:
var json; var urllevel= '/first_level'; var api = 'http://my.api.call.com'; var re = /^\d+/g; // regex match filename (decide if json has filenames or urls; files start digits or end extension) var loopapiurl = new array(); var recursion = false; // problem - how recursively build url's based on returned data i.e. traverse "unknown" tree function recursepxjson(){ if (!recursion) { loopapiurl = []; } // json $.get(api+urllevel+'/'+loopapiurl.join('/'),function(data,status){ (var in data) { if (!re.test(data[i].id)) { // {id: 'this_is_to_be_appended_to_url', id:'another_appendable'} recursion = true; loopapiurl.push(data[i].id); recursepxjson(); } else { // {id:'001200.file.ext',id:'001300.file.ext'} load(api+urllevel+'/'+loopapiurl.join('/')+'/'+data[i].id); recursion = false; } } }); //loaddbs(param); } // load renderable json - solved function load(param){ $.get(param, function(data, status){ json = json.stringify(data); var title = data.title.split(':'); html = '<h2>'+title[0]+'</h2>'; html += '<h3>'+title[1]+'</h3>'; html += '<h5>values:</h5>'; (var i=0; i<data.variables.length; i++) { html += '<b>'+data.variables[i].text+': </b>'; varlen = data.variables[i].valuetexts.length; if (varlen > 6) { html += '<i>'+data.variables[i].valuetexts[0]+', '+data.variables[i].valuetexts[1]+', '+data.variables[i].valuetexts[2]+' . . . '+data.variables[i].valuetexts[varlen-3]+', '+data.variables[i].valuetexts[varlen-2]+', '+data.variables[i].valuetexts[varlen-1]+'</i>'+'<b> (yhteensä '+varlen+' arvoa)</b>'; } else { html += '<i>'+data.variables[i].valuetexts.join(',')+'</i>'; } html += '<br/>'; } $(html+'<br>').appendto($('#tab2')); }); }
edit: @ moment seems each loop before begins another. therefore starts 1 in loop , if instatiated won't run before fist 1 done.
main loop internal loop 1 internal loop 2 <- isn't 1 should done first?
handle
loopapiurl
variable parameter functionrecursepxjson()
.get rid of useless
recursion
boolean.
you may find easier ditch jquery , make use of plain old xmlhttprequest. code longer but you'll gain better control of doing.
Comments
Post a Comment