Search code examples
javascriptjsonpretty-print

Javascript Pretty Print Format is giving wrong result


function output(inp) {
      document.body.appendChild(document.createElement('pre')).innerHTML = inp;
  }


  function searchInGitRepo(str) {
    const http = new XMLHttpRequest();
    http.open("GET", "https://api.github.com/search/repositories?q=" + str);
    http.send();
    http.onload = () => {
      var result = http.responseText;
      var strformat = JSON.stringify(result, undefined, 4);
      output(strformat);
    }
  }

  var result = searchInGitRepo('ecommerce');

I want to get data from github reponsitories. Result is coming perfectly but data is not formatting. Please take a look my code. It should work. I have followed many solution. Nothing is working for me!

function searchInGitRepo(str) {
    const http = new XMLHttpRequest();
    http.open("GET", "https://api.github.com/search/repositories?q=" + str);
    http.send();
    http.onload = () => {
      var result = http.responseText;
      var strformat = JSON.stringify(result, undefined, 4);
      output(strformat);
    }
}

Output Function:

function output(inp) {
      document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

Solution

  • JSON.stringify() is used to convert objects into strings. It's usually used when sending data to a web server because those data has to be a string.

    In your case, the data result that you are getting back from the server are already string, thus you don't need to "stringify" it.

    Use output(result); instead of output(strformat);