首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将HTML DOM结构转换为JSON

将HTML DOM结构转换为JSON
EN

Stack Overflow用户
提问于 2011-11-03 10:06:08
回答 5查看 13.5K关注 0票数 8

我浪费了那么多时间在this..the递归部分是相当虚幻的。

对于一个未知深度的HTML结构,我需要转换为JSON。

(我使用的是我正在构建的YAML i18n翻译系统)

我的总体想法是深入到找到INPUT为止,然后用span.innerHTML/input.value的键/值创建一个对象,并返回该对象,因此它将是最后到达的键的值。

(是的,这有点复杂,但很有趣)

JSBIN游乐场 -活代码示例

我无法使递归函数正常工作,无法输出我想要的JSON .

HTML结构

代码语言:javascript
复制
<ul>
    <li>
        <span class="title">footer</span>
        <ul>
            <li>
                <span>statement</span>
                <input type="text" value="xxx">
            </li>
        </ul>
    </li>
    <li>
        <span class="title">landing</span>
        <ul>
            <li>
                <span>page_title</span>
                <input type="text" value="yyy">
            </li>
            <li>
                <span>page_sub_title</span>
                <input type="text" value="xxx">
            </li>
            <li>
                <span class="title">pricing</span>
            <ul class="level11">
                <li>
                    <span>title</span>
                    <input type="text" value="aaa">
                </li>
                <li>
                    <span>cost</span>
                    <input type="text" value="xxx">
                </li>
            </ul>
            </li>
        </ul>
    </li>
</ul>

(需要) JSON输出

代码语言:javascript
复制
{
    footer : {
        statement : 'xxx'
    },
    landing : {
        page_title : 'yyy',
        page_sub_title : 'xxx',
        pricing : {
            title : 'aaa',
            cost : 'xxx'
        }
    }
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-11-03 10:52:09

如果您可以说服自己使用jQuery,请尝试

代码语言:javascript
复制
function helper(root) {
  var result = {};

  $('> ul > li > span', root).each(function () {
    result[$(this).text()] = $(this).hasClass('title') ? helper($(this).parent()) : $(this).next('input').val();
  });

  return result;
}

console.log(helper('body'));
票数 5
EN

Stack Overflow用户

发布于 2011-11-03 11:52:12

我是新来的,我找不到怎么发表评论。我想问你这是不是一直都是这样的结构,不管是哪个部门。如果答案是否定的,那就不要读我的答案:)。

因此,首先,我添加了一个函数getPrevious,因为直接尝试获取前面的兄弟节点会返回一个文本节点。接下来,我稍微修改了递归,因为它不是简单的递归,json格式(父-子关系)与html格式不同。我又试了两个等级,没问题。我希望它能帮上忙,如果不是的话,我很抱歉。

代码语言:javascript
复制
    function getPrevious(element)
    {
        var prev_el = element.previousSibling;
        while (prev_el.nodeType == 3)
        {
            prev_el = prev_el.previousSibling;
        }
        return prev_el;
    }

    function recursive(element){
        //var classname = element.className.split(' ');
        // element.nodeName == 'UL'
        var Result = {"title": '', "json": {}};
        var json = {};
        var cur_json_key = '';
        if( element.nodeType == 3 )
            return;
        else{
            //console.log( element.nodeType, element );

            var nodeName = element.nodeName.toLowerCase();
            var nodeClass = element.className.toLowerCase();

            // if this is the SPAN with class 'TITLE', then create an object with the innerHTML as KEY
            // and later the value should be another object, returned from the recursion...
            if( nodeName == 'span' && nodeClass == 'title' ){
                json[element.innerHTML] = {};
                Result.title = element.innerHTML;
                Result.json = json;
            }
            else
            if( nodeName == 'input' ){
                // if this is an INPUT field, then the SPAN sibling before it is the KEY.
                var key = getPrevious(element).innerHTML;
                var val = element.value;
                Result.json[key] = val;
            }
            else
            {
                var is_title_found = 0;
                var title_found = '';
                var res = {}
                // go deeper
                for( var child=0; child < element.childNodes.length; child++ ){
                    //json = $.extend( {}, recursive( element.childNodes[child] ));
                    res = recursive( element.childNodes[child]);
                    if (res)
                    {
                        if (res.title != '')
                        {
                            is_title_found = 1;
                            title_found = res.title;
                        }
                        else
                        {
                            $.extend(true, json, res.json);
                        }
                        console.log(JSON.stringify(json));
                    }
                }
                if (title_found)
                {
                    Result.json[title_found] = json
                }
                else
                {
                    Result.json = json;
                }
            }
            return Result;
        }
    }
票数 9
EN

Stack Overflow用户

发布于 2015-08-29 15:50:10

代码语言:javascript
复制
<section id="in">
    <ul>
        <li><div>lorem</div></li>
        <li>
            <div>lorem</div>
            <ul>
                <li><div>lorem</div></li>
                <li>
                    <div>lorem</div>
                </li>
                <li>
                    <div>lorem</div>
                    <ul>
                        <li><div>lorem</div></li>
                        <li>
                            <div>lorem</div>
                        </li>
                        <li><div>lorem</div></li>
                        <li><div>lorem</div></li>
                    </ul>
                </li>
                <li><div>lorem</div></li>
            </ul>
        </li>
        <li><div>lorem</div></li>
        <li><div>lorem</div></li>
    </ul>
</section>

<textarea id="outjson"></textarea>

    var a = [];
    getJSON($('#in'), a);
    function getJSON(el, arr)
    {
        el.children().each(function()
        {
            arr.push({});
            arr[arr.length-1][this.tagName] = [];
            if ($(this).children().length > 0)
            {
                getJSON($(this), arr[arr.length-1][this.tagName]);
            }
        });
    }
    $('#outjson').text(JSON.stringify(a));

你会得到:

[ {"LI":[{"DIV":[]},{“UL”:[{“DIV”:[]}},{“LI”:{“DIV”:[]}},{“LI”:[{“DIV”:[]}},{“DIV”:[]},{“UL”:[{“DIV”:[]}]}{“LI”:[{“DIV”:[]},{“LI”:[{“DIV”:[]} {"LI":[{"DIV":[]}]} } {"LI":[{"DIV":[]}]} ]

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7993066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档