Javascript Pretty Print Format is producing inaccurate output

function displayData(info) {
      document.body.appendChild(document.createElement('pre')).innerHTML = info;
  }


  function searchInGitHub(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 formattedData = JSON.stringify(result, undefined, 4);
      displayData(formattedData);
    }
  }

  var result = searchInGitHub('ecommerce');

I am trying to retrieve information from GitHub repositories. The response is correct, but the data is not being formatted as expected. Kindly review my code and help me resolve this issue. I have tried several solutions, but none seem to work for me!

function searchInGitHub(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 formattedData = JSON.stringify(result, undefined, 4);
      displayData(formattedData);
    }
}

Display Data Function:

function displayData(info) {
      document.body.appendChild(document.createElement('pre')).innerHTML = info;
}

Answer №1

JSON.stringify() function is commonly used to convert objects into strings, particularly when data needs to be sent to a web server where string format is required.

In this scenario, the data returned from the server in the variable result is already in string format, eliminating the need for stringifying it again.

Simply replace output(strformat); with output(result); in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angular JS version 1.2.26 to implement promises within a forEach iteration

I am working on a JavaScript project where I have implemented an angular.forEach loop to iterate over image configuration objects and create Image() objects using the URLs from the config. My goal is to ensure that none of the resulting images are returne ...

Facing difficulties in Angular 8 while trying to import firestore and firebase for an authentication system

While attempting to implement Firestore/Firebase functionalities for Google OAuth signin, I encountered an error indicating that Firebase is not imported: https://i.sstatic.net/oL4rY.png CODE: ERROR in node_modules/@angular/fire/auth/auth.d.ts:4:28 - er ...

Transforming multi-layered form data into a JSON array structure for seamless integration with application/json

I'm currently developing a Laravel application and facing an issue with the $controller->wantsJson() method in the back-end. This method returns TRUE only if the content type of the request is set to application/json. jQuery.ajax({ type: ...

continuously repeating with each press of the enter key

Whenever I focus on the input field and press enter, everything works fine. However, if I do it again, the action is repeated multiple times depending on how many times I focus. $(document).delegate(".changeValue","focus one",function(){ $(this ...

Uploading files in NodeJS using the multer library

I am attempting to upload a file to a specific directory on the disk using the multer library. As I analyze the code, it seems that when a request is made, the file is taken from it and saved separately from the rest of the request. Is there a way to acces ...

Incorporating SEO for a Flash-Based Website

After reading through various discussions on this topic, it seems like my question still remains unanswered. We are gearing up to revamp our company's website in the coming months. Currently, our site is mostly text-based, which has helped us achieve ...

What is causing the component to render three times?

Below is the structure of my component: import { useEffect, useState } from "react"; function Counter() { const [count, setCount] = useState(0); console.log("comp run"); const tick = () => { setCount(count + 1); conso ...

utilizing the target attribute within a form to open the link in the current page

I have been working on a web application and implemented a drop-down menu using a form to display information about the selected category. However, I noticed that when an option is selected, the link opens in a new window instead of the same window. Below ...

Jackson Inheritance: Mapping Objects Based on Unique JSON Key Names

Here is the json structure: { "fields": [ {"expression": "count(*)"}, {"column": "field1"}, ] } To implement inheritance, classes are created as follows: @JsonTypeInfo( use = JsonTypeInfo.Id.NAME) @JsonSubTypes({ @JsonSubType ...

Several components utilizing a popup module

I have created a modal popup example where scrolling is disabled in the background but enabled within the pop-up itself. Check out my demo here: View Demo My challenge lies in implementing a grid of images on the website: Take a look at the type of grid ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

Fetching data from a ColdFusion component using AJAX

Having trouble performing an SQL COUNT on my database using AJAX through a cfc file, and I can't figure out how to retrieve the return variable. Here's the relevant section of the cfc file: <cffunction name="getSpeakerCount" access="remote" r ...

Retrieve data from Firestore using React and log it outside of the asynchronous function

Seeking a way to retrieve data from userRef and use it to initiate another asynchronous call to another document (e.g. bikes) in order to display that bikes doc on the page Currently, the userDetailslog in the Home screen function prints {"_U": ...

Endless loop of jquery textbox focus event

Currently, I am employing jQuery for validating textbox values. I have two textboxes - txt1 and txt2. For this purpose, I have created a jQuery function: $("#txt1").blur(function () { if ($("#txt1").val() == "") { $("#scarrie ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Tick the checkbox to indicate that I want to insert an image in the adjacent column for the same row

Every time I click on the checkbox, an image should appear in the adjacent column for that specific row. Despite using the addClass() method and targeting the td, the image is appearing in all rows instead of just the selected one. Could somebody help me ...

How can I display a Skeleton when pressing pagination buttons and then turn it off after 3 seconds?

Here is a snippet of my code featuring the use of a Skeleton as a placeholder for CardMedia: {loading ? ( <Skeleton variant="rectangular" width={308} height={420} animation="wave" /> ) : ( <CardMedia s ...

What is the best way to showcase two SVG clocks on a single webpage?

The issue arises when combining the desktop and mobile versions of the clock script. The first clock works fine on its own, but upon duplicating another set of scripts for the second clock, it encounters display problems. I have appropriately labeled the c ...