Search code examples
javascriptgetjson

getting api data using getjson javascript


I'm trying to use this api, to show data in my webpage. I want to fetch the data and display it on a html paragraph.... I am using getJSON, but I couldn't make it work.. I am using AJAX to make a request.

Sample of the json data

{  
   "status":true,
   "data":{  
      "h1":0,
      "h3":0,
      "h6":0,
      "h12":0,
      "h24":0
   }
}

getjson code

 $.ajax({
 type: "GET",
 url: "https://api.nanopool.org/v1/eth/avghashrate/1",
dataType: "json",
success: function(data) {

    var json = $.parseJSON(data);
   $('#results').html( json.data.h1);
}
 });

html code is

<div id="results"></div>

Solution

  • Just remove $.parseJSON(), because data is already an object.

    $(function() {
      $.ajax({
        type: "GET",
        url: "https://api.nanopool.org/v1/eth/avghashrate/1",
        dataType: "json",
        success: function(data) {
          console.log(typeof data); // -- Object
          var json = data;
          $('#results').html(json.data.h1);
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="results"></div>