如何将选定的HTML转换为Json?

时间:2015-12-29 03:38:55

标签: javascript jquery html json

我想将部分html代码保存为json作为文件,然后重新回顾html代码进行编辑。知道我该怎么办?

<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label class="draggable ui-widget-content clickableLabel" id="label1" >New Text</label>
        <input id='textbox1' class="clickedit" type="text" class="draggable" class="ui-widget-content" placeholder="Text Here"/>
        <div class="clearfix"></div>
    </div>
</div>


我是json的新手,请尽可能简化。我看过其他问题,但他们似乎没有解决我的问题

6 个答案:

答案 0 :(得分:13)

您要做的是序列化

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

答案 1 :(得分:2)

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    
}

答案 2 :(得分:1)

    var html = $('#TextBoxesGroup')[0].outerHTML;
    var temp = {"html":html}; 
    var obj  = JSON.parse(temp);
    console.log(obj); // shows json object  

您可以使用任何服务器端语言从obj制作json。

答案 3 :(得分:0)

您可以使用以下代码段将HTML转换为JSON字符串

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

您可以将此JSON字符串存储到数据库中,然后编辑解码时间并将其放在UI页面上。

答案 4 :(得分:0)

在w3school上查看此链接 https://www.w3schools.com/code/tryit.asp?filename=FR0BHTAPG78A

mytext = document.getElementById("xx").innerHTML;
var myObj = {innerHTML:"yyy"};
myObj.innerHTML = mytext;
myJSON = JSON.stringify(myObj);

答案 5 :(得分:0)

我使用递归函数来处理它

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

数据是html文本

list_tree_names(soup)

print(dic)

您可以在https://github.com/celerometis/html2json中看到json文件

相关问题