How to convert selected HTML to Json?

前端 未结 6 847
迷失自我
迷失自我 2020-12-03 14:27

I want to save part of my html code into json as a file then recap back the html codes for editing. Any idea how can i do it?

相关标签:
6条回答
  • 2020-12-03 14:55

    see this link on w3school https://www.w3schools.com/code/tryit.asp?filename=FR0BHTAPG78A

    var myObj, myJSON, myText, obj;
    myText = document.getElementById("xx").innerHTML;
    myObj = {innerHTML:"yyy"};
    myObj.innerHTML = myText;
    myJSON = JSON.stringify(myObj);
    
    0 讨论(0)
  • 2020-12-03 14:56

    You can use this following snippet to convert HTML into JSON string

    var HtmlToJsonString = JSON.stringify($("#TextBoxesGroup").html());
    

    You can stored this JSON string into database and edit time you decode it and put on UI page.

    0 讨论(0)
  • 2020-12-03 15:05
    function htmlToJson(div,obj){
     if(!obj){obj=[]}
     var tag = {}
     tag['tagName']=div.tagName
     tag['children'] = []
     for(var i = 0; i< div.children.length;i++){
        tag['children'].push(htmlToJson(div.children[i]))
     }
     for(var i = 0; i< div.attributes.length;i++){
        var attr= div.attributes[i]
        tag['@'+attr.name] = attr.value
     }
     return tag    
    }
    
    0 讨论(0)
  • 2020-12-03 15:13

    What you want to do is called serializing.

    //  This gives you an HTMLElement object
    var element = document.getElementById('TextBoxesGroup');
    //  This gives you a string representing that element and its content
    var html = element.outerHTML;       
    //  This gives you a JSON object that you can send with jQuery.ajax's `data`
    // option, you can rename the property to whatever you want.
    var data = { html: html }; 
    
    //  This gives you a string in JSON syntax of the object above that you can 
    // send with XMLHttpRequest.
    var json = JSON.stringify(data);
    
    0 讨论(0)
  • 2020-12-03 15:15
        var html = $('#TextBoxesGroup')[0].outerHTML;
        var temp = {"html":html}; 
        var obj  = JSON.parse(temp);
        console.log(obj); // shows json object  
    

    You can use any server side language to make a json from obj.

    0 讨论(0)
  • 2020-12-03 15:17

    i use recursive function to handle it

    from bs4 import BeautifulSoup
    dic = dict()
    
    itt = 0
    
    def list_tree_names(node):
    global itt
    for child in node.contents:
        try:
            dic.update({child.name +"/"+ str(itt): child.attrs})
            itt += 1
            list_tree_names(node=child)
        except:
            dic.update({"text" +"/"+ str(itt): child})
            itt += 1
    
    
    soup = BeautifulSoup(data, "html.parser")
    

    data is the html text

    list_tree_names(soup)
    
    print(dic)
    

    you can see json file in https://github.com/celerometis/html2json

    0 讨论(0)
提交回复
热议问题