1

I am Java Developer, but have a small task in Jquery. I have to get Json data parsed.... JSON data is as follows:

   [
   {"category":"Soups","menu_item":"Tomato Soup","type":"veg"},
   {"category":"Starters","menu_item":"Summer Salad","type":"veg"},
   {"category":"Main Course","menu_item":"Black Beans Chicken","type":"non-veg"},
   {"category":"Soups","menu_item":"Lentil Soup","type":"veg"},
   {"category":"Starters","menu_item":"Roasted Root Veg","type":"veg"},
   ]

And am Trying this code but I am not getting expected result...... I am trying to get the tags in div but no idea I am getting just.. .

[object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object] [object Object]

The code that I used is.............

    $.getJSON("data.json",function(result){
       $.each(result, function(i, field){
         $("div").append(field + " ");
       });
    });
3
  • when you are looping through the array and placing field, you are just placing the javascript object in the dom, that's why it is displaying [object Object] Commented Aug 9, 2013 at 7:57
  • each field is an object, you need to get it's properties, for example: field.category Commented Aug 9, 2013 at 7:57
  • The JSON is not valid. Remove the last , at {"category":"Starters","menu_item":"Roasted Root Veg","type":"veg"}, ] Otherwise as the guys wrote about the iteration... Commented Aug 9, 2013 at 8:57

2 Answers 2

3
$.each(result, function(i, field){
    $("div").append(field.category + " ");
});
Sign up to request clarification or add additional context in comments.

1 Comment

I would go with a standard for loop since it faster but thumbs up.
1

result is an Array of objects.

field is the entire object in each iteration..

field 1st iteration - {"category":"Soups","menu_item":"Tomato Soup","type":"veg"}

You would need to use a specific key to get the value

field.category which would give you Soups for the first iteration

.append(field.category + " ");

You have 3 keys in each object category , menu_item and type

So use the key on the object to access a specific value.

Check Fiddle

Comments

Your Answer

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