James121
James121

Reputation: 45

How to JSON parse a multi element array?

Trying to bring over data from PHP. I'm using the urls to display images and then I'm using the tags to reorder the array I'm trying to create called data. I'm not sure if I'm parsing correctly.

var data = [];

function importJson(str) {

    if (str == "") {
        document.getElementById("content").innerHTML = "";
        return;
    }
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }


    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            data = JSON.parse(xmlhttp.response);
            alert(xmlhttp.response);
            alert(data);

            for (var sport_index = 0; sport_index < data.sport.length; sport_index++) {
                var url1 = data.sport[sport_index][1];
                alert(data.sport);
            }
            alert(url1);
        }
    }

    xmlhttp.open("GET", "http://server/~name/folder/many.php");
    xmlhttp.responseType = "json";
    xmlhttp.send();

    function buildImage(imagesrc) {
        var img = document.createElement('img');
        img.src = imagesrc;
        document.getElementById('content').appendChild(img);
    }

}

xmlhttp.response looks like this

{"sport":[{"ImagesId":"34","ImagesPath":"http:\/\/server\/~name\/folder\/images\/24-08-2014-1408868419.png","Tag":"sport"},{"ImagesId":"30","ImagesPath":"http:\/\/server\/~name\/folder\/images\/23-08-2014-1408824125.png","Tag":"sport"}],"clothes":[{"ImagesId":"33","ImagesPath":"http:\/\/server\/~name\/folder\/images\/23-08-2014-1408824179.png","Tag":"clothes"},{"ImagesId":"32","ImagesPath":"http:\/\/server\/~name\/folder\/images\/23-08-2014-1408824166.png","Tag":"clothes"}],"food":[{"ImagesId":"31","ImagesPath":"http:\/\/server\/~name\/folder\/images\/23-08-2014-1408824158.png","Tag":"food"}]} 

But data looks like [object Object] and when I try to use the urls to create images the elements are undefined.

Upvotes: 1

Views: 86

Answers (1)

therealrootuser
therealrootuser

Reputation: 10894

In a Javascript object, you access elements by name, for instance:

data.sport[sport_index]["ImagesPath"]

Or

data.sport[sport_index].ImagesPath

Upvotes: 2

Related Questions