bill_cosby bill_cosby - 6 months ago 22
jQuery Question

How to convert html tree in to a customized json tree using jquery?

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


to

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


As of now, I know the basics of jQuery, JavaScript. I need to know where to start thinking in order to accomplish the above conversion.

And the html tree could be more complex with more children.

Answer

Thanks @Alexandru and @Nenad for giving a start. I have been able to complete this on my own. Below is the function that generates 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
}

Below is the code that calls that function:

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