So, i have a script that gets JSON from a server and displays it to a page, the JSON has html in it which has to be displayed, but for some reason when i try to convert the extracted JSON(which has the html div i want) to a string the contents are lost and i get an empty object.
i want to convert it to a string so innerHTML can insert it to the page
iv'e tried to convert it using String(obj) and obj.toString() and JSON.stringify all of them return an empty object
event just trying to insert the data without turning it into a string displays an empty object on the page
here's the json:
{
"content": {
"rendered": "<div id=aboutnf><p>lorem ipsum</p></div>",
"protected": false
}
}
and here's the javascript:
function displayContents() {
//if the request succeeds display the contents
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
//parse the JSON
var JsonObj = JSON.parse(httpRequest.responseText);//parse the response
var content = JsonObj.content;
console.log(content);
var StrContent = JSON.stringify(content);
//parse the html from the json
var parser = new DOMParser();
var stuff = parser.parseFromString(StrContent, "text/html");
//get the div we want
var disp = stuff.getElementById(aboutnf);
console.log(disp);
console.log(typeof(disp));
//convert it to a string
var dispContents = String(disp);
console.log(dispContents);
//insert it to the page
document.getElementById('stuff').innerHTML = dispContents;
//if the request failed report it
} else {
alert('There was a problem with the request.');//if it fails report the fail
}
}
}
when i console.log the extracted div from the JSON it shows up fine with the contents:
console.log(disp);
//returns:
<div id=aboutnf><p>lorem ipsum</p></div>
console.log(typeof(disp));
//returns:
object
but after converting to a string:
console.log(dispContents);
//returns:
[object HTMLDivElement]
and inserting it to the page shows the same thing: an empty HTMLdivElement
document.getElementById('stuff').innerHTML = dispContents;
//puts:
[object HTMLDivElement]
//on the page instead of the contents of the div
how do i convert the JSON object into a string without losing all its contents?
i would prefer not to use jQuery for this.
Edit:
I used JsonObj.content.rendered and then appendchild()
to get the div I wanted from the json
thanks Nesaje, Patrick Roberts and nnnnnn
document.getElementById('stuff').appendChild(disp);.JSON.stringify(), that turns an object back into a JSON string. The object you got viaJSON.parse()has the value you need in a propertyJsonObj.content.rendered.