25

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?

<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 simplified if possible.I had look at other questions but their don't seem to address my question

yan
  • 369
  • 1
  • 4
  • 13
  • 1
    _"html code into json as a file"_, Do you mean create an object that contains the code, convert it to JSON, then put into a file that can then be downloaded to client computer, or uploaded to your server? – Patrick Evans Dec 29 '15 at 03:49
  • @PatrickEvans something like that. But instead of letting others to download, i need to recap the file for further editing – yan Dec 29 '15 at 03:55
  • 2
    Possible duplicate of [Map HTML to JSON](http://stackoverflow.com/questions/12980648/map-html-to-json) – repzero Dec 29 '15 at 04:34

6 Answers6

28

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);
lleaff
  • 4,249
  • 17
  • 23
  • 11
    `var json = JSON.stringify({html:html})`, that is JSON. What you have is simply a javascript object, no such thing as a "JSON object". – Patrick Evans Dec 29 '15 at 03:48
  • That is true, the reason I kept it in object form is because of the `jquery` tag in the question. Changed the variable name to avoid confusion. I will keep the "JSON object" wording though, it captures the meaning of an object that serializes into JSON without losing information. – lleaff Dec 29 '15 at 03:50
  • @lleaff i got this error --> Cannot read property 'outerHTML' of null – yan Dec 29 '15 at 03:52
  • @yan That means there is no element with the `id` corresponding to the one you gave to the function `document.getElementById()` @PatrickEvans See what I mean by trying to read the author's mind, I doubt they care whether {} is just a POJSO or not. – lleaff Dec 29 '15 at 03:55
  • 3
    I took the OP to mean they wanted a JSON representation of the DOM HTMLElement object, eg JXON or similar : https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML – Anthony Dec 29 '15 at 04:00
  • @lleaff there is an id call TextBoxesGroup. I copy and paste the id so it shouldn't have an problem – yan Dec 29 '15 at 04:01
  • @yan - You are wrong. If you are getting that error, that means NULL is being returned for the `getElementById` part. Don't rely on whether you can see it or not, instead back up and confirm what value the script gets for just that part of the code, like `console.log(document.getElementById('TextBoxesGroup');` – Anthony Dec 29 '15 at 04:06
  • @Anthony it return null but why? – yan Dec 29 '15 at 04:12
7
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    
}
Nilesh Chavan
  • 361
  • 3
  • 10
2

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

1

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);
glinda93
  • 7,659
  • 5
  • 40
  • 78
0

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.

Arulkumar
  • 12,966
  • 14
  • 47
  • 68
Jatin Patel
  • 57
  • 1
  • 4
0
    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.

Shijin TR
  • 7,516
  • 10
  • 55
  • 122