Mr.Richway Mr.Richway - 1 year ago 102
JSON Question

Use css class/id from JSON key

I'm fairly new to JSON and the json file I'm working with has HTML elements in certain keys. Here's an example of data in an array I'm trying to pull.

"com" : "<p class=\"body-line ltr \"><span class=\"heading\">HEADING</span></p><p class=\"body-line ltr \">BODY</p>"

As expected, when it's pulled onto the page it's just displayed as text:

"<p class="body-line ltr "><span class="heading">HEADING</span></p><p class="body-line ltr ">BODY</p>"

How can I remove the HTML elements from the text and use them in my own web page? Keeping in mind that I can't actually edit the json file.

I'm using vue and vue resource.

Answer Source

Now that I know what you're asking --

You need to actually add the element to the DOM in order for it to show up as HTML on your page; until then, it is just a string.

There are many ways to do this, such as jQuery .append() if you use jQuery, or document.appendChild() if you have an object and want to use plain old JavaScript, or you can also set the innerHTML of an element using JavaScript to include the new contents.

I will provide one example here, using plain JS and innerHTML of a Div.

You get json from somewhere that looks like:

json = { "com" : "some HTML in here" }

You might have container some div like this on the page:

<div id="container"></div>

Then, wherever your JavaScript is, you could set the innerHTML of the container:

var containerDiv = document.getElementById("container")
containerDiv.innerHTML = json["com"]

This should give you enough direction to roll with this.

Here's my small example working in a jsFiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download