Spankaroonie
Spankaroonie

Reputation: 155

Convert JSON string to HTML

I have a json object which contains some HTML. For example:

{
    "cat": "1",
    "catUrl": "this-is-a-url",
    "catSummary": "This is a summary with <a href=\"http://www.a.com\">a link</a>"
},

Notice catSummary has an href in it. But it doesn't get rendered as a link. Instead it just renders as regular text..

enter image description here

How do I make this work as a proper link?

EDIT
Just to clarify, I am using the VueJS framework, not jQuery. A simple solution (that I completely missed..) is using the v-html directive.

Upvotes: 5

Views: 8013

Answers (4)

user9534295
user9534295

Reputation:

You can get your json property "catSummary" and set into HTML controls

$("#" + elementId).innerHTML = "This is a summary with <a href=\"http://www.a.com\">a link</a>";

Upvotes: 0

user3146115
user3146115

Reputation:

You can use below method after getting "catSummary" value from your json

$.parseHTML("This is a summary with <a href=\"http://www.a.com\">a link</a>")

Above method load your string as HTML and you can load into any element, See Reference

Upvotes: 0

renlund86
renlund86

Reputation: 1

Do you use any library ? For example with jQuery you could simply do like this:

var data = {
    "cat": "1",
    "catUrl": "this-is-a-url",
    "catSummary": "This is a summary with <a href=\"http://www.a.com\">a link</a>"
};

$("body").html(data.catSummary); 

and it will render as a link.

Upvotes: 0

Divij Sehgal
Divij Sehgal

Reputation: 655

In case all you want to do is populate another html element with the content in the catSummary field, use following:

$('#element_id').innerHTML = object_name.catSummary;

This will populate the element's object with the content in catSummary field.

Upvotes: 3

Related Questions