0

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++)
          {

          }

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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];
}

Comments

0
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);
});

Comments

0

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]); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.