user3347455
user3347455

Reputation: 51

How can I access elements in an array?

I have a problem with getting data from JSON array.

Here is the JSON code:

[
  [
    4.440216064453125,
    [1,0,0,0,1,1,1,0,0,1,1],
    0,
    "Test0",
    "Test0",
    [129]
  ],
  [
    4.452216148376465,
    [1,0,0,0,1,1,1,1,1,0,0],
    1,
    "Test1",
    "Test1",
    [1,0,0]
  ]
]

And i want to alert "1" value. It is "Test1".

Here is JS code:

function inspect(){ 
    $.ajax({
        type: "GET",
        url: 'addtest.json',
        dataType: "JSON",
        async : false,
        success: function(JSON) {
            alert(JSON.array[1])
        },

        error: function(JSON) {
            alert("Error")
        }
    });
} 

It's not working properly.

Could you please help ?

Upvotes: 0

Views: 81

Answers (3)

Sohil Desai
Sohil Desai

Reputation: 2988

Check this it will help you to access array. Comment shows the position of element in array.

[
  [
    4.440216064453125,  // <- [0][0]
    [
        1, // <- [0][1][0]
        0, // <- [0][1][1]
        0, // <- [0][1][2]
        0, // <- [0][1][3]
        1, // <- [0][1][4]
        1, // <- [0][1][5]
        1, // <- [0][1][6]
        0, // <- [0][1][7]
        0, // <- [0][1][8]
        1, // <- [0][1][9]
        1 // <- [0][1][10]
    ], // <- [0][1]
    0,// <- [0][2]
    "Test0",// <- [0][3]
    "Test0",// <- [0][4]
    [129]// <- [0][5]
  ], // <- [0]
  [
    4.452216148376465,// <- [1][0]
    [
        1, // <- [1][1][0]
        0, // <- [1][1][1]
        0, // <- [1][1][2]
        0, // <- [1][1][3]
        1, // <- [1][1][4]
        1, // <- [1][1][5]
        1, // <- [1][1][6]
        1, // <- [1][1][7]
        1, // <- [1][1][8]
        0, // <- [1][1][9]
        0 // <- [1][1][10]
    ],// <- [1][1]
    1,// <- [1][2]
    "Test1",// <- [1][3]
    "Test1",// <- [1][4]
    [1,0,0]// <- [1][5]
  ] // <- [1]
]

Upvotes: 0

Quentin
Quentin

Reputation: 944532

The outer level of your JSON data consists of an array.

You are treating it as an object with a property named array.

Also, don't call your argument JSON, you'll make the (useful) JSON object that is built into browsers.

Test1 is a value of an array that is a member of an array that is a member of the outer most array. You can access it by drilling down through each array in turn.

    success: function(data) {
        alert(data[1][3])
    },

Upvotes: 1

Ranganadh Paramkusam
Ranganadh Paramkusam

Reputation: 4368

JSON is an defined object in JavaScript, use another variable

function inspect(){ 
    $.ajax({
        type: "GET",
        url: 'addtest.json',
        dataType: "JSON",
        async : false,
        success: function(response) {
            alert(response[1][3]);   // For showing "Test1"
        },

        error: function(err) {
            alert(err)
        }
    });
} 

Upvotes: 1

Related Questions