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?

1 Answer 1

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"

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.