0

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

Please I get this following json string in my ajax side :

    {
    "products": [
        {
            "id":            48,
            "quantity":      1,
            "priceByLine":   "950,00 €",
            "name":          "Filtre Mixte",
            "price":         "950,00 €"

        }],   

    "total": "950,00 €",
    "productTotal": "950,00 €"
   }

To get the total price, I just have to do :

alert(data.total);

But when I want to get the Id, I do :

alert(data.products.id); 

It gave me undefined !

Please masters, how could I do to get the id ?

Thanks in advance !

Community
  • 1
  • 1
Sami El Hilali
  • 981
  • 3
  • 12
  • 21

4 Answers4

1

Products is an array containing one element of type object. Hence you should type:

alert(data.products[0].id);

Your statement would have been valid if the structure was:

{
"products": 
    {
        "id":            48,
        "quantity":      1,
        "priceByLine":   "950,00 €",
        "name":          "Filtre Mixte",
        "price":         "950,00 €"

    },   

"total": "950,00 €",
"productTotal": "950,00 €"
}
closure
  • 7,412
  • 1
  • 23
  • 23
1

Well, data.products is an Array, so you can't get the id of that Array, you need to try and lookup a property of each element within it.

For example, this would give you a result:

 alert(data.products[0].id);

But, you can try looping through that data:

 data.products.forEach(function(product) {
      alert(product.id);
 });

Note the above forEach won't work in bad old browsers (including IE8), but it will work in anything modern. Use a for loop if you need to support older ones.

Bartek
  • 15,269
  • 2
  • 58
  • 65
1

I'm not sure but if you try this :

alert(data.products[0].id); 

Because products key seem to be an array, but with only one row.

Nonow Dev
  • 98
  • 5
0

try this.. since your products is in array

alert(data.products[0].id); 
bipen
  • 36,319
  • 9
  • 49
  • 62