javascript 如何将HTML DOM结构转换为JSON?

tzxcd3kk  于 2023-03-21  发布在  Java
关注(0)|答案(5)|浏览(138)

递归部分是相当虚幻的。
对于一个给定的HTML结构,未知的深度,我需要转换为JSON。

  • (我使用的是我正在构建的一些YAML国际化翻译系统)*

我的总体思路是深入到找到INPUT,然后用span.innerHTML/input. Value的键/值创建一个对象,并返回该对象,因此它将是最后到达的<span class="title">的KEY的VALUE。
JSBIN playground -实时代码示例

我无法让我的递归函数输出我想要的JSON...

HTML结构

<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输出

{
    footer : {
        statement : 'xxx'
    },
    landing : {
        page_title : 'yyy',
        page_sub_title : 'xxx',
        pricing : {
            title : 'aaa',
            cost : 'xxx'
        }
    }
}
mspsb9vt

mspsb9vt1#

我是新来的,我不知道如何发表评论。我想问你,无论哪个部门,这是否总是结构。如果答案是否定的,那么不要读我的答案:)。
所以首先我添加了一个函数getPrevious,因为直接尝试获取前一个兄弟节点会返回一个文本节点。接下来我稍微改变了一下递归,因为它不是一个简单的递归,json格式(父子关系)与html格式不同。我又尝试了2个级别,它还可以。我希望它有帮助,如果没有,我很抱歉。

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;
        }
    }
rhfm7lfc

rhfm7lfc2#

如果你能说服自己使用jQuery,试试this

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'));
mfpqipee

mfpqipee3#

<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));

您将获得:
[{" UL ":[{" LI":[{" DIV ":[]}]}、{" LI":[{" DIV ":[]}、{" UL":[{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI ":[{" DIV":[]}]}、{" LI":[{" DIV":[]}]}、{" LI":[{" DIV":[]}]}}、{" LI":[{" DIV":[]}]}}、{" LI":[{" DIV":[]}}]}}、{

lx0bsm1f

lx0bsm1f4#

试试这个:

function helper(root) {
  var result = {};

  root.querySelectorAll(':scope > ul > li > span').forEach(function (obj) {
      result[obj.innerText] = obj.classList.contains('title') ? helper(obj.parentNode) : obj.parentNode.querySelector('input').value;
  });

  return result;
}

console.log(helper(document.querySelector('body')));
91zkwejq

91zkwejq5#

实时示例

var ul = document.body.firstElementChild;
// cheat to only extract the value (key is undefined)
var data = extractKeyValue({}, ul)[1];

function extractKeyValue(span, thing) {
  // return key & input value
  if (thing.tagName === "INPUT") {
      return [span.textContent, thing.value];
  } else {
    // recurse over every li and return the key/value of the span + thing
    var obj = {};
    [].forEach.call(thing.children, function (li) {
      var span = li.firstElementChild;
      var thing = span.nextElementSibling;
      // tuple is [key, value]
      var tuple = extractKeyValue(span, thing);
      obj[tuple[0]] = tuple[1];
    });
    return [span.textContent, obj];
  }
}

相关问题