简体   繁体   English

递归遍历未知的json对象/树和基于返回的json的操作

[英]Recursive traversal of unknown json object/tree and actions based on returned json

I'm using a API that returns JSON on request. 我正在使用一个可应要求返回JSON的API。 This JSON has either names for next level URL's or a filename. 此JSON具有下一级URL的名称或文件名。

The problem is that code has to recognize which JSON is returned. 问题在于代码必须识别返回了哪个JSON。

If JSON only has a names for next url levels then create url and get it. 如果JSON仅具有下一个URL级别的名称,则创建URL并获取它。 Then recursively get a new set of names or files, recognize and do it over. 然后以递归的方式获取一组新的名称或文件,进行识别并重新进行。 It can go as menu levels deep as required. 可以根据需要将菜单级别调高。 1 to * 1至*

If it has a filename it should get it and render it as html. 如果它具有文件名,则应获取它并将其呈现为html。 (This is already solved) (已经解决)

Example of json 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 would turn into http://my.api.call.com/New_url_1_level_1.../New_url1_level_2/ ... 这些将变成http://my.api.call.com/New_url_1_level_1.../New_url1_level_2/ ...

The problem is that how to loop over URL's and to finally get to filename for example: http://my.api.call.com/New_url_1_level_1/New_url_1_level_2/New_url_1_level_3/001300.file.ext 问题是如何循环访问URL并最终获得文件名,例如: 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 to match filename (decide if json has filenames or urls; files always start with digits or end with extension)

        var loopApiUrl = new Array();
        var recursion = false;
        // This is the problem - how to recursively build url's based on returned data i.e. traverse a "unknown" tree
        function recursePxJson(){
                if (!recursion) {
                    loopApiUrl = [];
                }
// Get JSON
            $.get(api+urllevel+'/'+loopApiUrl.join('/'),function(data,status){

                for (var i 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 - ALREADY 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>';

                for (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&auml; '+varlen+' arvoa)</b>';
                    } else {
                        html += '<i>'+data.variables[i].valueTexts.join(',')+'</i>';
                   }
                    html += '<br/>';

                }

                $(html+'<br>').appendTo($('#tab2'));
            });
            }

EDIT: At the moment it seems like it is does each for loop before it begins another. 编辑:此刻似乎是每个for循环在开始另一个循环之前。 Therefore it starts one in loop and if another is instatiated it won't be run before the fist one is done. 因此,它开始一个循环,如果另一个被初始化,则在第一个完成之前不会运行。

Main loop Internal Loop 1 Internal Loop 2 <- Isn't this the one that should done first? 主循环内部循环1内部循环2 <-这不是首先应该做的吗?

  1. Handle your loopApiUrl variable as a parameter for your function recursePxJson() . loopApiUrl变量作为函数recursePxJson()的参数进行处理。

  2. Get rid of the useless recursion boolean. 摆脱无用的recursion布尔值。


You may find it easier to ditch jQuery and make use of a plain old XMLHTTPRequest. 您可能会发现抛弃jQuery并使用普通的旧XMLHTTPRequest更容易。 Your code will be slightly longer but you'll gain a better control of what your doing. 您的代码将稍长一些, 但是您将更好地控制自己的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM