Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple jquery plugin for converting json to html

I need to append this json data to an html element.

[
    {
        "website":"google",
        "link":"http://google.com"
    },
    {
        "website":"facebook",
        "link":"http://fb.com"
    }
]

How to convert this easily using any plugin.Presently,I couldn't find any simple plugins in jquery,So please help me friends.

Thanks in advance..........

like image 734
Vaisakh Pc Avatar asked Jun 02 '14 04:06

Vaisakh Pc


5 Answers

Hi you can use jPut jQuery Plugin (http://plugins.jquery.com/jput/)

Create a HTML jPut Template

<div jput="template">
  <a href="{{link}}">{{website}}</a>
</div>
<div id="main">
</div>

<script>
$(document).ready(function(){
var json=[{"website":"google","link":"http://google.com"},
    {"website":"facebook","link":"http://fb.com"}];

   $('#main').jPut({
       jsonData:json,   //your json data
       name:'template'  //jPut template name
   });
});
</script>
like image 130
shabeer Avatar answered Oct 21 '22 02:10

shabeer


jPut is easy to use comparing to normal parsing. if there is lots of data to be appended it is very difficult to append using $.each loop. in jPut just need to create template & to print the data just put the object name in {{}}.

like image 21
Harish U Warrier Avatar answered Oct 21 '22 04:10

Harish U Warrier


With jQuery, you could do something like this:

data = $.parseJson(json);

$.each(data, function(key, obj) {
    htmlElement = $('<a href="'+link+'">'+website+'</a>');
    $('body').append(htmlElement);
})
like image 39
Benjamin David Avatar answered Oct 21 '22 03:10

Benjamin David


Why use a plugin for this? No need to write a plugin to go around this. Just simply loop it through & do what you wan't with the data. Here is an example:

var data = [
    {
        "website":"google",
        "link":"http://google.com"
    },
    {
        "website":"facebook",
        "link":"http://fb.com"
    }
];

var html = '';

$.each(data, function (index, item) {
    html += '<a href="' + item.link + '">' + item.website + '</a>';
});

$('body').append(html);
like image 29
danniehansenweb Avatar answered Oct 21 '22 03:10

danniehansenweb


If you're expecting it to be an anchor tag then -

Html -

<div id="siteContainer"></div>

JS-

var sites = [
    {
        "website":"google",
        "link":"http://google.com"
    },
    {
        "website":"facebook",
        "link":"http://fb.com"
    } 
]

var $container = $('siteContainer');

$(sites).each(function(item, index){
    var name = item['website'];
    var link = item['link'];
    var anchorTag = '<a href="' + link + '">' + name + '</a>');
    $container.appendTo(anchorTag);
});
like image 1
VtoCorleone Avatar answered Oct 21 '22 04:10

VtoCorleone