开发者

How to extract info from json output

开发者 https://www.devze.com 2023-01-08 13:56 出处:网络
I have a json output that looks like this.. { 开发者_C百科 \"XXXX\": { \"name\": \"Dalvin Nieger\",

I have a json output that looks like this..

{
  开发者_C百科 "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.


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.


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


once you fix the json it should look like this and work like this

var jsonData = {
   "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"
   }
}
$.each(jsonData,function(id,data){
  var content = '<p>ID : '+id;
  if(typeof data == 'object')
    $.each(data,function(index,value){
        
     if(typeof value == 'object' && index=='work'){
       content += '<br/>'+index+' : '+value.department.name;
      }else
        content += '<br/>'+index+' : '+value;       
    });
  content += '</p>';
  $('#result').append(content);
   
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<div id="result">
  </div>

0

精彩评论

暂无评论...
验证码 换一张
取 消