views:

100

answers:

2

Hi,

I have a json output that looks like this..

{
   "XXXX": {
      "name": "Dalvin Nieger",
      "work": [
         {
            "department": {
               "name": "Sales"
            },
            "start_date": "0000-00"
         }
      ],
      "link": "http://www.my-site.com/profile.php?id=XXXXX",
      "id": "XXXXXX"
   },
   "XXXXXXX": {
      "name": "Nick Mercer",
      "work": [
         {
            "department": {
               "name": "Marketing"
            },
            "start_date": "0000-00",
            "end_date": "0000-00"
         }
      ],
      "link": "http://www.my-site.com/profile.php?id=XXXXXX",
      "id": "XXXXXX"
   }
}

Where XXXX is the id no. of the employee. I want to loop through the data and get id no., name, department he works in and end date for each employee using javascript.

I appreciate any help.

Thanks.

+6  A: 

Your JSON isn't correct - it's wrapped in an array but you don't use keys in JSON arrays. If you changed the outer brackets ([) to braces ({) you'd just be able to loop through the JSON object keys in JavaScript. See here for instructions.

Skilldrick
+1  A: 

I'm not sure I completely understand the question, but would this do what you want, assuming you'll fix the problem with your JSON as pointed out?

for(i in jsonData) {
  console.log("id is " + i);
  console.log("name is " + jsonData[i].name);
  console.log("department is " + jsonData[i].work[0].department.name);
  console.log("enddate is " + jsonData[i].work[0].end_date);
}
kander
Actually, it's `jsonData[i].work[0].department.name`, as `work` contains a (redundant) array. Otherwise, +1.
Skilldrick
Thanks for catching that; corrected it in the answer. BTW: it's redundant in this dataset, but I can imagine someone having two functions after eachtother - both with different startdates.
kander
@kander, yes you're right. Worth bringing attention to either way, as the view code would have to change to accommodate multiple departments if used.
Skilldrick