Render Json Into Html
Solution 1:
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>')
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Solution 2:
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
Solution 3:
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, functionfoo(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 htmlvar encoded = '<div style="background:#FF0">Hello World</div>';
// Temp div to render html internallyvar decode = $('<div />').html(encoded).text();
// Add rendered html to DOM
$('#output').append(decode);
Solution 4:
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));
Solution 5:
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.
Post a Comment for "Render Json Into Html"