Alexandre
Alexandre

Reputation: 759

Problems accessing multidimensional array

So i'm running a $.getJSON statement and i'm having some problems... here's the json:

{
    "K-6608-1-0": [
        {
            "Info": [
                {
                    "SVGFile": "46658.svg",
                    "Name": "Faucet Parts"
                }
            ],
            "Parts": [
                {
                    "Cod":"70012",
                    "Name":"Ruela de Parafuso Reforçado B2",
                    "Price":"$100"
                },
                {
                    "Cod":"71131",
                    "Name":"Parafusasdasdasdsdao Reforçado B2",
                    "Price":"$45"
                },
                {
                    "Cod":"78208",
                    "Name":"Tubo de Conexão R2D2",
                    "Price":"$150"
                }
            ]
        }
    ]
}

So, let's say i've made the getJSON that way:

$.getJSON('test.json', function(data){
   alert(data["K-6608-1-0"]["Info"]["SVGFile"]);
})

Why this code doesn't return "46658.svg"? Where's the error?

Thanks in advance ^^

Upvotes: -1

Views: 66

Answers (3)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

K-6608-1-0 and Info are arrays, so you have to set the position.

alert(data["K-6608-1-0"][0]["Info"][0]["SVGFile"]);
                         ^          ^

Upvotes: 3

Danilo Valente
Danilo Valente

Reputation: 11342

That's because data["K-6608-1-0"] is an array, so to access the property you want, first you have to access an element of this array bi its index (data["K-6608-1-0"][0]["Info"] is also an array):

$.getJSON('test.json', function(data){
    alert(data["K-6608-1-0"][0]["Info"][0]["SVGFile"]);
    //                       ^          ^
});

Upvotes: 2

Marc B
Marc B

Reputation: 360572

alert(data["K-6608-1-0"][0]["Info"]["SVGFile"]);
                        ^^^--- add this

you've got arrays nested in objects nested in arrays nested in.... The first K-whatever is actually an array. You'll probably have to do the same for deeper levels as well.

Upvotes: 0

Related Questions