Razinar
Razinar

Reputation: 767

Convert innerHTML into a custom json with javascript

This is an example of innerHTML i get from a text editor on a web page where user can write text and add images, videos and audios.

<p>This is a<br>test</p>
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/12345" frameborder="0" allowfullscreen=""></iframe></p>
<p><audio controls><source src="https://www.test.com/123/456/example.mp3"/></audio></p>
<p>end of test</p>

I save the innerHTML so i can reload the contents written by the user inside the editor, but i also need to format those information in json structure like the following:

{
  "page1": {
     contents: [
        {"text":"This is a test"},
        {"video":"https://www.youtube.com/embed/12345"},
        {"audio":"https://www.test.com/123/456/example.mp3"},
        {"text":"end of test"}       
     ]
  }
}

this json should be sent to the backend and saved, so a mobile app can ask for those information and display them in a customized way. Maintaining elements' order is crucial.

So, how can i obtain the above structure from innerHTML in javascript? I'm madding out on it

Upvotes: 0

Views: 4229

Answers (2)

Nuspeed1
Nuspeed1

Reputation: 126

If the format never changes, you can try converting innerHTML to string, then split by </p>. This will create an array of 4 elements. Loop through each element. For strings, stripping tags from strings can easily be done with string.replace("<p>",""). For the more complicated iframe and audio tags, use this regex "(https.*?)". It will return the src url. Then create your objects with those values. Here's some quick pseudo code:

var aHtml = JSON.stringify(element.innerHTML).split('</p>');


var result = [];
aHtml.forEach(function(item, idx, arr){
    // run regex against it, grab matching element
    var match = item.match(/"(https.*?)"/,"g");
    if(match){
        var url = match[1]; // the url
        if(match[0].indexOf('audio')> -1){
            result.push({audio: url});      
        }else{
            result.push({video: url});
        }
        
    }else{
        var str = item.replace(/(<p>|<br>)/g, " ");
        result.push({text: str});
    }
})

console.log(result);

Upvotes: 0

Maharshi Patel
Maharshi Patel

Reputation: 51

Hope this might give you a basic idea:

1) You need to select different keys for start text and end text like start_text and end_text.

2) Create a virtual DOM element and store the innerHTML string you have in the innerHTML of DOM element. This will help you to access DOM methods and you can achieve what you want. Ex:

var content = '(innerHTML content)';
var d = document.createElement("DIV");
d.innerHTML = content;
var p_tags = d.querySelectorAll("p");

3) Create your preferred object structure. Ex:

var final_content = {};
final_content["page_1"] = {};
final_content["page_1"]["content"] = [];
final_content["page_1"]["content"].push({"start_text":""}); 

4) Finally, you can convert object to JSON string with JSON.stringify(final_content).

Upvotes: 1

Related Questions