Skip to content Skip to sidebar Skip to footer

Render Json Into Html

I get JSON data with next code: $.getJSON( 'data.json',function foo(result) { $.each(result[1].data.children.slice(0, 10), function (i, post) { $(

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.

mohsen1/json-formatter-js

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: normaldark

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 = '&lt;div style="background:#FF0"&gt;Hello World&lt;/div&gt;';

// Temp div to render html internallyvar decode = $('<div />').html(encoded).text();

// Add rendered html to DOM
$('#output').append(decode);

DEMO

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"