D. 777KLM
D. 777KLM

Reputation: 470

Put JSON data with the same name into different divs

I have JSON file with this structure:

{
  "launches": [{
    "name": "First Name"
  }],
  "launches": [{
    "name": "Second Name"
  }],
  "launches": [{
    "name": "Third Name"
  }],
  "launches": [{
    "name": "Fourth Name"
  }]
}

I add the data like this:

$('#div-name').append(d.name);

When this is displayed on a webpage, it is placed in one div with no spaces. I can add a <p> tag to the append, but that still displays ALL the data and creates new divs to display it.

Basically, what I am trying to do is to create a div for each separate "name" value and display only one value per div.

Upvotes: 0

Views: 1182

Answers (2)

DeFeNdog
DeFeNdog

Reputation: 1210

A slightly different way of going about it:

var data = {
  "names": [
    "Falcon 9",
    "Orion",
    "PSLV",
    "Soyuz"
  ]
};

$.each( data["names"], function( key, value ) {
    $('#div-name').append(value+"<br />");
});

Upvotes: 0

balexandre
balexandre

Reputation: 75103

First of all, your "json" is not a valid json, remmeber that in a json object, you can not have duplicated keys. You can easily use an online validator to help you with that... and after you fix it, let's assume that what you actually have is an array of objects like:

[
    {"name": "Falcon 9"},
    {"name": "Orion"},
    {"name": "PSLV"},
    {"name": "Soyuz"}
]

with this valid json, you can easily loop trough all the elements like (and take that you are using jQuery):

var json = [ ... ];

$(function() {
    $.each(json, function(i, item){
        $("p").append("<div>" + item.name + "</div>");
    });
});

here's a live test: https://jsbin.com/bixadegeye/1/edit?html,css,js,output

Upvotes: 4

Related Questions