Pawan
Pawan

Reputation: 32331

How to parse this JSON containing single array

I am getting JSON in this format

[
    {
        "toppings": [
            "Honey with Chocolate Sauce  10 ML",
            "Honey with Carmel  10 ML"
        ]
    }
]

Could anybody please tell me how can i get the elements present under the toppings ??

I have tried to parse this way , but giving me undefined .

for(var k=0;k<toppingres[0].length;k++)
          {

          }

Upvotes: 0

Views: 38

Answers (4)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Basically you have an array and inner array is at its 0 index so you can get them this way:

$.each(data,function(index,item){

    $.each(item,function(index1,item1){
console.log(item1);
    });
});

FIDDLE EXAMPLE

or:

$.each(data[0].toppings,function(index,item){
    console.log(item);
}

FIDDLE

or more simply:

console.log(data[0].toppings[0]);
console.log(data[0].toppings[1]);

FIDDLE

Upvotes: 2

Dave Briand
Dave Briand

Reputation: 1744

Fiddle: http://jsfiddle.net/GWM7b/

and code:

var myJSON = [{ "toppings": [ "Honey with Chocolate Sauce 10 ML", "Honey with Carmel 10 ML" ]}]; for (var i = 0; i < myJSON[0].toppings.length; i++){ alert(myJSON[0].toppings[i]); }

Upvotes: 0

martinezjc
martinezjc

Reputation: 3555

var data=[
{
    "toppings": [
        "Honey with Chocolate Sauce  10 ML",
        "Honey with Carmel  10 ML"
        ]
    }
];

// prevents duplicated object
$.each(data,function(index,item){
  console.log(item);
});

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36458

Assuming toppingres is the full object represented by the JSON, toppingres[0] isn't an array, so it has no length.

You mean to say:

var toppings = toppingres[0].toppings;

for ( var k = 0; k < toppings.length; ++k )
{
  var topping = toppings[k];
}

Upvotes: 0

Related Questions