Reputation: 63
I get JSON data with next code:
$.getJSON(
"data.json",function foo(result) {
$.each(result[1].data.children.slice(0, 10),
function (i, post) {
$("#content").append( '<br> HTML <br>' + post.data.body_html );
}
)
}
)
<div id="content"></div>
Some of strings included : <
and >
and this did not displaying as regular html <
, >
Try to use .html()
instead .append()
did not work.
Here is live example http://jsfiddle.net/u6yUN/
Upvotes: 6
Views: 51697
Reputation: 6691
Just use the 3rd (space
) parameter of JSON.stringify to format the json, and use <pre>
tags to display.
const json = { foo: { bar: 'hello' } }
$('html').append('<pre>' + JSON.stringify(json, null, 2) + '</pre>')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 10
Reputation: 1774
Another library that works for rendering JSON objects is: renderjson
Although it has a minimalistic style, it allows to click through the JSON structure.
Example usage:
document.getElementById("test").appendChild (renderjson (data));
Upvotes: 4
Reputation: 5026
You may want to give JSON2HTML a try. Works with native JavaScript, with jQuery and with node.js. Allows to completely customize the generated HTML.
Upvotes: 1
Reputation: 65785
If you're looking for a nice collapsible render I've written a module to this. It's in pure JavaScript so you can use it in any framework.
It's also available as an AngularJS directive if you are using AngularJS mohsen1/json-formatter
Checkout the demo here: AngularJS directive demo
It's also theme-able, so you can change the colors:
Upvotes: 5
Reputation: 48600
Here is whet you were asking for: Complete JSFiddle Demo
var jsonRequestUrl = 'http://www.reddit.com/r/funny/comments/1v6rrq.json';
var decoder = $('<div />');
var decodedText = '';
$.getJSON(jsonRequestUrl, function foo(result) {
var elements = result[1].data.children.slice(0, 10);
$.each(elements, function (index, value) {
decoder.html(value.data.body_html);
decodedText += decoder.text();
});
$('#content').append(decodedText);
});
Edit: Keeping this here as a simpler example.
// Encoded html
var encoded = '<div style="background:#FF0">Hello World</div>';
// Temp div to render html internally
var decode = $('<div />').html(encoded).text();
// Add rendered html to DOM
$('#output').append(decode);
Upvotes: 5
Reputation: 10555
One of the easiest way is
var t= post.data.body_html;
t.replace('<','<').replace('>', '>');
$("#content").append( '<br> HTML <br>' + t );
Upvotes: 0
Reputation: 4656
Use $.parseHTML()
jQuery method
var myData = "yourHtml with <" //
$("#content").append($.parseHTML(myData));
Here it is a jsfiddle: http://jsfiddle.net/x4haw/
Upvotes: 0