如何使用jquery将html树转换为自定义的json树?

时间:2016-05-24 09:08:26

标签: javascript jquery html json

<ul id='parent_of_all'>
<li>
  <span class='operator'>&&</span>
  <ul>
    <li>
      <span class='operator'>||</span>
      <ul>
        <li>
          <span class='operator'>&&</span>
          <ul>
            <li>
            <span class='condition'>1 == 1</span>
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
  <ul>
    <li>
      <span class='condition'>1 != 0</span>
    </li>
  </ul>
</li>
</ul>

{"&&":[{'||':[ {'&&':[ {"lhs": "1", "comparator": "==", "rhs":"1"} ]} ] } , {"lhs": "1", "comparator": "!=", "rhs":"0"}]}

截至目前,我已经了解了jQuery,JavaScript的基础知识。我需要知道从哪里开始思考才能完成上述转换。

对于更多孩子来说,html树可能会更复杂。

3 个答案:

答案 0 :(得分:1)

您需要一种方法来选择li的第一级,我假设您有一个父元素,其ID为list。我使用基本的jquery编写了以下代码,以便您可以理解它。

var result = {};

var $all_li = $('#list').children('li');     // selecting the first level of li
for(var i in $all_li){                       // iterating all_li using for (you may use forEach )  

    var $current_li = $( $all_li[i] );                       // getting operator from first span
    var operator = $current_li.children('span').html();      // the text of the operator

    var $inner_spans = $current_li.find('>ul >li >span');    // getting list of children spans (from path $list>li>ul>li>span)
    var li_spans = [];                                       // an array where we will put the inner span objects
    for(var j in $inner_spans){ // iterating the inner spans
        var text = $($inner_spans[j]).html().split(" ");     // splitting the html
        li_spans.push({
            lhs: text[0],
            comparator: text[1],
            rhs: text[2]
        });                                // adding the splitted html to an object. Note: error if text didn't have 2 white spaces
    }

    result[operator] = li_spans;          // adding the operator key and li_spans value to the result json
}

此代码将解析html并构造result json,它应该适用于您提供的html格式。请记住,它不处理错误(例如错误的树格式)。  simmiar html格式。

答案 1 :(得分:1)

您可以使用eachmap

执行此操作

&#13;
&#13;
var obj = {}
var span = $('li > span').not('ul li span').text();

$('ul li span').each(function() {
 var text = $(this).text().split(' ');
 obj[span] = (obj[span]||[]).concat({lhs: text[0], comparator: text[1], rhs: text[2]});
});

console.log(obj)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <span>&&</span>
  <ul>
    <li>
      <span>1 == 1</span>
    </li>
  </ul>
  <ul>
    <li>
      <span>1 != 0</span>
    </li>
  </ul>
</li>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

感谢@Alexandru和@Nenad的开始。我已经能够自己完成这个。 下面是生成json的函数。

function prepare_json(current_node){
    var object = {}
    var span = $(current_node).children('span')
    if (span.hasClass('condition')){
        var text = span.html().split(" ");
        object = {lhs: text[0], comparator: text[1], rhs: text[2]}
    }
    else if(span.hasClass('operator')){
        var operator = span.text()
        object[operator] = (object[operator] || [])
        var children = $(current_node).children('ul').children('li')
        for(var i = 0; i < children.length; i++){
            var child_pql = prepare_json([children[i]])
            object[operator].push(child_pql)
        }
    }
    return object
}

以下是调用该函数的代码:

var parent_node = $('#parent_of_all').children('li')
var json = JSON.stringify(prepare_pql_json(parent_node), null, 2)