How to convert selected HTML to Json?

I want to save part of my html code in json as a file, and then return the html codes for editing. Any idea how I can do this?

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


I am new to json, please simplify if possible. I looked at other questions, but they do not seem to be affected by my question.

+10
source share
5 answers

What you want to do is called serialization.

 // 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 `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); 
+13
source
  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 json from obj.

+1
source

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

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

You can save this JSON string to the database and edit its decoding time and put it on the user interface page.

0
source

see this link to 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); 
0
source

I use a recursive function to handle this

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

 list_tree_names(soup) print(dic) 

You can see the JSON file at https://github.com/celerometis/html2json

0
source

Source: https://habr.com/ru/post/1239387/


All Articles