views:

23

answers:

2

Hi! I need to know how one would put the following JSON into elements with a class name of article using jQuery AND just some basic JavaScript:

{"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]}

Trying to achieve the below HTML. I'm very new to JSON, etc. Looking to learn how by example..

<div class="article">
    <h5>story 1</h5>
    <p>By: journalist 1</p>

    <h5>story 2</h5>
    <p>By: journalist 2</p>
</div>
+3  A: 
var data = {
    "elements": [
        {
            "head": "story 1",
            "writer": "journalist 1"
        },
        {
            "head": "story 2",
            "writer": "journalist 2"
        }
    ]};

var result = []; /* where we will store the generated HTML */

$.each(data.elements, function() {
    /* in this function, `this` refers to one of the [story] objects in the elements array */
    result.push('<h5>');
    result.push(this.head);
    result.push('</h5><p>By: ');
    result.push(this.writer);
    result.push('</p>');
});

$('<div class="article" />') /* creates the div class="article" */
    .html(result.join('')) /* merges the generated HTML from above and inserts it into the div*/
    .appendTo(document.body); /* appends the div to the page */
Alexander Gyoshev
+1 for using each() function and arra.push
naikus
Thanks Alexander. I'll give it a shot. Appreciate your answer!
Lynn
+1  A: 

Its quite straightforward using jQuery. Use the append function:

var jsonObj = {"elements": [
    {
        "head": "story 1",
        "writer": "journalist 1"
    },
    {
        "head": "story 2",
        "writer": "journalist 2"
    }
]};

var article = $(".article");
var items = jsonObj["elements"];

var arr = [];    

for(var i = 0, len = items.length; i < len; i++)   {
   var itm = items[i];
   arr.push("<h5>" + item["head"] + "</h5><p>By: " + item["writer"] + "</p>");
}

article.append(arr.join(""));
naikus