Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

javascript - convert HTML DOM structure to JSON

I have wasted so much time on this..the recursion part is quite illusive.
for a given HTML structure, of unknown depth, I need to convert to JSON.
(I use this from some YAML i18n translation system I am building)

my general idea is to go deep until it finds the INPUT, then create an object with the key/value of the span.innerHTML/input.value, and return that object, so it will be the VALUE of a KEY that is the last <span class="title"> reached.

(Yes, it's a bit complicated but very interesting to develop)

JSBIN playground - live code example

I can't get my recursive function to work properly, to output the JSON I want...

HTML structure

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


(Wanted) JSON output

{
    footer : {
        statement : 'xxx'
    },
    landing : {
        page_title : 'yyy',
        page_sub_title : 'xxx',
        pricing : {
            title : 'aaa',
            cost : 'xxx'
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm new here and i couldn't find how to post a comment. I wanted to ask you if this is always the structure, no matter the dept. If the answer is no, then don't read my answer :).

So first of all i added a function getPrevious, because directly trying to get the previous sibling returns you a text node. Next i changed the recursion a little bit, because it's not a simple recursion, the json format (the parent-child relations) is different then the html format. I tried it for 2 more levels and it's ok. I hope it's helpful and sorry if it's not.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...