Reputation: 140
I need to create a layout which will display JSON data in HTML div
tags.
Something like the h4
tag for titles, p
tag for descriptions and img
tag for pictures.
What is the best and simplest way to do this?
Upvotes: 0
Views: 1554
Reputation: 3349
There are bajillions of ways you could do this. JQuery tends to make the sort of DOM manipulation you are looking for easier and I personally recommend it, but there's no reason you couldn't use Vanilla JS.
Assuming you choose to go the JQuery route, here's a JFiddle to get you started: https://jsfiddle.net/Lf7j3xst/1/
Basically you'll want to parse the json into an object and then iterate over the values in it, appending data to your document as appropriate. What you do here very much depends on the particular json format in question, so this is just an example since I have no idea what data your processing.
Example json my code is based on:
{
"title": "Hello",
"image": "https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150",
"paragraph": "Lorem ipsum dolor sit amet, nam ut iracundia appellantur. An nibh impedit dolorem eos, dico definitiones vix an, pri ad simul tollit. Quo aperiri admodum appetere id. Duo harum consulatu ea, etiam altera deleniti ea sea, atqui nominavi scripserit vel cu. Ut nam errem choro iuvaret, sea natum rationibus no. Maiestatis disputationi ad mel."
}
Example code:
var parsed = JSON.parse(example);
$.each(parsed, function(key, item) {
if (key == "image") {
$('#main').append('<img src="' + item + '" />');
}
if (key == "title") {
$('#main').append('<h1>' + item + '</h1>');
}
if (key == "paragraph") {
$('#main').append('<p>' + item + '</p>');
}
})
This should be enough to get you started. Spend some time reading the JQuery documentation.
Upvotes: 2