1

I'm trying to get specific information from a JSON file (Squarespace) with the aim of appending it to a <div>. I need to loop through the data and get the location from each post. This is the code I'm using:

$.getJSON("http://www.theluxedit.com/?format=json-pretty", function(data) {
    $.each(data, function(index, value) {
        $('.locationData').append(data.items.location.addressLine2);
    });
});

It will only work if I specifiy the item using an integer, such as:

$('.locationData').append(data.items[1].location.addressLine2);

This seems to be working for other examples I've tried, am I maybe getting the JSON concatenation wrong?

stark
  • 2,246
  • 2
  • 23
  • 35

1 Answers1

2

The issue is you need to iterate through the items themselves rather than the entire object returned:

var $locationData = $('.locationData');
$.getJSON("http://www.theluxedit.com/?format=json-pretty", function(data) {
    $.each(data.items, function(index, item) {
        $locationData.append(getLocationEl(item.location.addressLine2));    
    });
});

function getLocationEl(address) {
    return $('<div>', { text: address });
}

By doing this, each iteration will look at a different item. You can then access properties on that item directly, rather than from the top-level data returned.

Also, I am assuming this is being run on theluxedit.com. Otherwise you will get an error. See this for more info: "No 'Access-Control-Allow-Origin' header is present on the requested resource"

Community
  • 1
  • 1
akosel
  • 1,183
  • 9
  • 14
  • Just as an aside comment, its inefficient to do a complete DOM search for a class inside the loop.. store the result in a variable before the loop and use the reference. – Ben Cummins Oct 13 '16 at 18:29
  • Updated the answer. If you want the text to be on separate lines, this works well. You could also use a span instead of a div. Additionally, you could just accumulate all the values and append them as comma-separated list in a single string. – akosel Oct 13 '16 at 18:45