Accessing data in a multidimensional JSON array with jQuery
Solution 1
Inside your success function you can treat the JSON data as a JavaScript object. You can access the product array and objects inside it like this:
console.log(data.products + " product(s) in data"); // data.products is 2 (integer)
for(var i = 0; i < data.products; i++) { //
var product = data[i.toString()]; // 0.toString() is "0"
// data["0"] is what you want
// now product points to the property "0"
console.log(product.product_no); // so you can use product.xxx
// or product["xxx"]
} // likewise for "1", "2", "3" and so on
Replace console.log
with alert
if you do not know what console is.
Solution 2
Each of the product details can be accessed through data[iProductIndex.toString()]
member. Data is stored inside data["0"]
and data["1"]
, therefore to access them you need to convert integer value to string. Unfortunately you won't be able to use $.each
loop because "0" and "1" are separate member objects. Use for loop with iProductIndex
.
![dangermark](https://i.stack.imgur.com/uFUsC.jpg?s=256&g=1)
dangermark
Updated on June 14, 2022Comments
-
dangermark about 2 years
I am trying to work out how to access data in an essentially multidimensional JSON array.
My jQuery AJAX request looks like this:
$("#login-form").submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/ajax/login', data: 'email='+$("#email").val()+'&password='+$("#password").val(), success: function(data){ // FIRE ALERT HERE alert(data.firstname); }, dataType: 'json' }); });
This is what i am getting back. User account details, plus a list of products they have against their account.
{ "logged_in":true, "firstname":"Joe", "surname":"Bloggs", "Full_name":"Joe Bloggs", "email":"[email protected]", "phone":"+123456789", "website":"", "age":"26-35", "street":"1 Street Ave", "city":"Townland", "state":"NA", "postcode":"1234", "country":"Australia", "products":2, "0":{ "product_no":"1087", "customer":"2", "bought_from":"1", "date_of_purchase":"2011-04-08", "method":"instore", "invoice":"0", "current":"1" }, "1":{ "product_no":"24", "customer":"2", "bought_from":"1", "date_of_purchase":"2011-04-08", "method":"instore", "invoice":"0", "current":"1" } }
As you can see, i am alerting the first name, which is fine. I can access everything in the first dimension by using data.key but i'm not sure how then i need to index the next dimension. Obviously I would like to display each of the products somehow.
Suggestions would be most welcome.
-
dangermark about 13 yearsAny chance of a little example? I'm relatively new to jquery.
-
Anton about 13 years
data.products.length
returnsundefined
bcoz that "0" and "1" are not the child ofproducts
-
dangermark about 13 yearsThis is exactly what I was looking for. Thanks for poitning me in the right direction