4

I have following json data

[
  {
    id: "79",
    title: "Web+Infographics",
    path: "web-infographics"
  },
  {
    id: "80",
    title: "Miscellaneous",
    path: "miscellaneous"
  },
  {
    id: "81",
    title: "Entertainment",
    path: "entertainment"
  }
]

and i want to get the id, title and path out of it using jquery how can i do that? Thanks in advance.

yckart
  • 32,460
  • 9
  • 122
  • 129
Vishal Prajapati
  • 41
  • 1
  • 1
  • 4
  • It's just a `for` loop, what more do you need to know? – Barmar Jul 30 '13 at 13:06
  • One doesn't traverse json, one parses the json to create an object and then traverses the object. What you've shown in the question is not valid json, but is a valid array literal containing object literals - do you have a variable assigned to reference that array, or...? – nnnnnn Jul 30 '13 at 13:06
  • @nnnnnn Stop tilting at that windmill -- everyone on SO uses `json data` to refer to the object, not the JSON string. – Barmar Jul 30 '13 at 13:06
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Jul 30 '13 at 14:41

2 Answers2

11

Quite simple, use jQuery.each:

$.each(data, function (index, item) {
  console.log(item);
});

But, you don't really need jQuery for this simple task, give the native Array.prototype.forEach a try:

data.forEach(function (item) {
  console.log(item);
});

If you have to support older browsers and don't want to depend on a library, a for-loop could to the trick:

for (var i = 0; i < data.length; ++i) {
  var item = data[i];
}
yckart
  • 32,460
  • 9
  • 122
  • 129
  • You probably wouldn't with to include jQuery just for this, but if you have jQuery already you absolutely should use jQuery.each. – Tmdean Jun 17 '15 at 19:35
  • @Tmdean Could you explain your "strict" thoughts about the *absolutliness*?! – yckart Jun 18 '15 at 22:11
  • Judging by your italics and interrobang I think you're taking this way more seriously than I meant it, but I was thinking that it's generally considered a best practice to use hasOwnProperty when iterating through a JavaScript object, and if you use a well tested library function you won't have to worry about that or other similar details. – Tmdean Jun 19 '15 at 01:21
4
<script>

var data = [
  {
    id: "79",
    title: "Web+Infographics",
    path: "web-infographics"
  },
  {
    id: "80",
    title: "Miscellaneous",
    path: "miscellaneous"
  },
  {
    id: "81",
    title: "Entertainment",
    path: "entertainment"
  }
];

$.each(data, function(key, value) {
    alert(value.id + ", " + value.title + ", " + value.path);
});

</script>
MightyPork
  • 18,270
  • 10
  • 79
  • 133