Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Json as key and value in the Ajax $.getJSON()?

I have this ajax code for getting json from Jobs.json file.

 $(document).ready(function(){
        $('#btn2').click( callJobs );
        });

function callJobs()
{


     alert("getting results...");
    $.getJSON('Jobs.json', function(JSON){
        $('#result').empty();

        $.each(JSON.jobs, function(i, JOB){
            $('#result')
            .append(JOB.Job +'<br />')
            .append(JOB.Priority+'<br />')
            .append(JOB.DueDate+'<br />')
            .append(JOB.Iscompleted+'<hr />');
      });
    });
}

Jobs.json code is below.

{
"jobs":[
  {
     "Job":"Job1",
     "Priority":"Low",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  },
  {
     "Job":"Job2",
     "Priority":"High",
     "DueDate":"11.03.2013",
     "Iscompleted" : "No"
  },
  {
     "Job":"Job3",
     "Priority":"Medium",
     "DueDate":"11.03.2013",
     "Iscompleted":"No"
  }
  ]
  }

Now I want to rewrite $.each function dynamically.That is, it will write the json string as key and value instead of .append() .

like image 307
ntf Avatar asked Feb 02 '26 11:02

ntf


1 Answers

This would walk over the properties of each job dynamically:

$.getJSON('Jobs.json', function(JSON){
    var $container = $('#result').empty();

    $.each(JSON.jobs, function(i, JOB) {
        $.each(JOB, function(key, value) {
            $container.append(key + ': ' + value + '<br />');
        });
        $container.append('<hr />');
    }
});

Demo

like image 110
Ja͢ck Avatar answered Feb 05 '26 01:02

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!