skip to Main Content

I wish to loop through my JSON array returned by my API [{"a":1},{"b":2},{"c":3},{"d":4}]. How do parse the JSON key and value onto my html so the output div gives only the key and value.

<body> 
  <div id = "result" style = "color:green" ></div>      
  <script type = "text/javascript">
      $(document).ready(function() {

          $.ajax({
              url: "http://localhost:8080/api/",
              type: 'GET',
              dataType: 'json',
              success: function(res) {
                  console.log(res);

                  //var data=$.parseJSON(res);
                  //var data = JSON.stringify(res)

                  $.each(res, function(key, value) {
                      console.log(key);
                      console.log(value);

                      var para = document.createElement("P");
                      para.innerHTML = key + ":" + value;

                      document.getElementById("result").appendChild(para);
                  })
              }
          });
      }) 
  </script> 
</body>

2

Answers


  1. You are looping through array ,function will take arguments as item and index:

    $.each(array, function(index,item){});
    

    Make a secondary loop and iterate through objects:

    $.each(object, function(key,value){});
    
    res = [{
        "a": 1
    }, {
        "b": 2
    }, {
        "c": 3
    }, {
        "d": 4
    }]
    $.each(res, function(index,item) {
    $.each(item, function(key,value){
        var para = document.createElement("P");
        para.innerHTML = key + ":" + value;
        document.body.appendChild(para);
    });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. Your JSON format is an array, with each key an object

    [
      {"a" : 1},
      {"b" : 2},
      {"c" : 3},
      {"d" : 4}
    ]
    

    So this means that when you loop through the items, the key will be the index of the array, and the value will be the object

     $.each(res, function(key, value) {
        console.log(key); // -> will be 0, 1, 2 etc
        console.log(value); // -> will be {"a" : 1}, {"b" : 2}, etc
    });
    

    So there are 2 options, you can either change your API to return a single object with the key:value pairs like this

    {
        "a" : 1,
        "b" : 2,
        "c" : 3,
        "d" : 4
    }
    

    Or you need to add an extra loop in your code, so that you can loop through the objects and display the values (although I would recommend to rather go with the first option

    $.ajax({
        url: "http://localhost:8080/api/",
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            $.each(res, function(key, object) {
                $.each(object, function(key, value) {
                    var para = document.createElement("P");
                    para.innerHTML = key+ ":" +value;
                    document.getElementById("result").appendChild(para);
                });
            });
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search