Issue
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
Solution
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).
Answered By - Maharshi Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.