【问题标题】:how to parse a tree into JSON object with jQuery [duplicate]如何使用 jQuery 将树解析为 JSON 对象 [重复]
【发布时间】:2018-05-10 20:10:54
【问题描述】:

我正在尝试从树类构建 JSON 对象,我只需要跨度值。树结构是动态的和嵌套的,所以我认为最好的方法是使用一些递归函数。目前我只是成功提取了键和值,但没有成功构建 JSON 对象。

我在构建 html 文件时使用的是 jinja2。

这是html代码:

<div class="tree well">
            <ul id="treeList">
                <li >
                    <span id="deviceName" class="fa fa-tablet"> {{report["name"]}}</span>
                    <ul>
                        {% for v in report["reports"] %}
                        <li >
                            <span id="{{v['_id']}}" class="fa fa-code-fork"> {{v["_id"]}} </span>
                            <ul>
                                {% for key, value in v.items() recursive %}
                                    {% if key != '_id' %}
                                    <li  id="li_{{key}}">
                                        {% if value is not mapping %}
                                            {% if key == 'status' %}
                                                <span class="status" id="{{key}}"> {{value}}</span>
                                            {% elif key == 'issues' %}
                                                <span class="fa fa-bug issues" id="issues"> issues</span>
                                            {% elif key == 'updated_on' %}
                                                <span id="updateOn" class="fa fa-calendar-o "> {{value}} </span>
                                            {% endif %}

                                        {% endif %}
                                        {% if value is mapping  %}
                                            {% if key == 'attackProccess' %}
                                            <span id="attackProccess" class="fa fa-sitemap"> {{key}} </span>
                                            {% elif key == 'data' %}
                                            <span id="data" class="fa fa-database">  data </span>
                                            {% else %}
                                            <span id="{{key}}" class="fa fa-minus-circle"> {{key}} </span>
                                            {% endif %}
                                            <ul id="ul-attack-items">
                                                {{ loop(value.items())}}
                                            </ul>
                                        {% endif %}
                                    </li>
                                    {% endif %}
                                {% endfor %}
                            </ul>
                        </li>
                        {% endfor %}
                    </ul>
                </li>
            </ul>
        </div>

这是 jquery 部分:

// empty string to save the result
    var dataList = "";

    // find all li elements within the element with the id list
    var $entries = $("#treeList").find('span');

    // iterate through all these items, with i as index and item itself as entry
    $entries.each(function(i, entry) {

        // append the elements id attribute and its content to the string, like: item_1=Item1 for <li id="item_1">Item1</li>
        dataList += ' '+$(entry).attr('id') + ':' + $(entry).text();

        // add & to the string, if the entry is not the last one
        if (i != $entries.length-1) {
            dataList += '';
        }
        dataList = dataList.replace(/(\r\n|\n|\r)/gm,"");

这是我想要的模型:

{
"_id" : "aa:dd:ff:ff:cc:ac",
"account" : "iphonex@gmail.com",
"name" : "Iphone X",
"reports" : [ 
    {
        "updated_on" : "2017-11-27",
        "_id" : "iOS 11.1",
        "attackProccess" : {
            "item1" : {
                "status" : "todo"
            },
            "item2" : {
                "status" : "todo"
            },
            "item3" : {
                "status" : "todo"
            },
            "item4" : {
                "status" : "todo"
            },
            "item5" : {
                "status" : "todo"
            },
            "item6" : {
                "status" : "todo"
            }
        },
        "issues" : [],
        "data" : {
            "files" : {
                "status" : "todo"
            },
            "chats" : {
                "viber" : {
                    "status" : "todo"
                },
                "facebook" : {
                    "status" : "todo"
                },
                "instagram" : {
                    "status" : "todo"
                },
                "twitter" : {
                    "status" : "todo"
                },
                "skype" : {
                    "status" : "todo"
                },
                "telegram" : {
                    "status" : "todo"
                },
                "whatsapp" : {
                    "status" : "todo"
                },
                "line" : {
                    "status" : "todo"
                }
            },
            "sms" : {
                "status" : "todo"
            },
            "app_list" : {
                "status" : "todo"
            },
            "telegram" : {
                "status" : "todo"
            },
            "downloads" : {
                "status" : "todo"
            },
            "locations" : {
                "status" : "todo"
            },
            "catchapp" : {
                "status" : "todo"
            },
            "bookmarks" : {
                "status" : "todo"
            },
            "calendar" : {
                "status" : "todo"
            },
            "contacts" : {
                "status" : "todo"
            },
            "media" : {
                "status" : "todo"
            },
            "notes" : {
                "status" : "todo"
            },
            "posts" : {
                "status" : "todo"
            },
            "call_history" : {
                "status" : "todo"
            }
        }
    }
]

}

【问题讨论】:

  • 如果您可以向我们展示 HTML 输出而不是意大利面条模板,以及您尝试创建的对象格式的示例,将会更有帮助
  • 我发现html输出不正确但是我添加了我想要的模型。
  • HTML 不正确是什么意思?那意味着您的模板不正确。如果 HTML(即输入)不正确,我们如何建议代码以生成正确的 JSON 输出。 Rory 表示显示最终呈现到您的页面的 HTML,而不是您的模板代码。您的脚本作用于最终呈现的 HTML。这是您的功能的“输入”。您的模板基于其他一些我们看不到且不真正感兴趣的输入创建 HTML。从中创建的实际 HTML 是我们需要看到的。

标签: jquery html


【解决方案1】:

我终于用下面的代码解决了:

$('#saveReport').click(function() {
    $('#processing-modal').modal('show');
    setTimeout(function(){
        $('#processing-modal').modal('hide');
    }, 10000);
    var reportToJson = {};
    var mapkeyToDepth = {};
    $('ul.treeList').each(function(i, ul) {
        $(ul).find("li").each(function(j,li){
            // Now you can use $(ul) and $(li) to refer to the list and item
            var value = $($(li).children("span")).text();
            var key = ($($(li).children("span")).attr('id'));
            var reportDepth = $($(li).children("span")).parents('li').length;
            // console.log(li);
            if ($(li).hasClass('parent_li') ) {
                setReportValKey(reportToJson, mapkeyToDepth, key, null,reportDepth)

            } else {
                if (typeof key == "undefined") {
                    var key = ($($(li).children("span")).attr('class'));
                }
                if ($($(li).children("span")).hasClass('span_issue_url')) {
                    console.log(reportDepth)
                    value = $($(li).children("span")).attr('title');
                    key =   ($($(li).children("span")).find('a:first').attr('href')).split("https://")[1]

                    console.log(key)
                    console.log(value)
                }
                if ($($(li).children("span")).hasClass('add_issues')) {
                    return true;
                }

                setReportValKey(reportToJson, mapkeyToDepth, key, value,reportDepth);
            }
        });
    });

    if (reportToJson) {
        $.ajax({
            url:'/updateReportDocument',
            data:JSON.stringify({'report':reportToJson,
                'mac':$('.macAddress').text(),
                'attack':djangoData['name']}),
            dataType: 'json',
            contentType: 'application/json',
            type:'POST',
            success: function(response){
                $('#processing-modal').modal('hide');
                if(response.hasOwnProperty('error')){
                    console.log(response);
                }else{
                    location.reload();
                }
            },
            error: function(error){
                $('#processing-modal').modal('hide');
                console.log(error);
            }
        });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    相关资源
    最近更新 更多