XMLHttpRequest and JSON

Hello,

I am working on the challenge Get JSON with the JavaScript XMLHttpRequest Method and I had a question about parsing the JSON data.

Here is the example code:

const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
  const json = JSON.parse(req.responseText); *
  document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
};

My question is, if the GET request returns the responseText as a string by default, then wouldn’t it be redundant to use JSON.parse() in line * only to JSON.stringify() it back to a string in the next line?

Couldn’t we just add the responseText to the HTML element by doing something like:
document.querySelector('.message').innerHTML = req.responseText

Thank you.

I am guessing that we use JSON.parse() because we might need it in object format for other things, and it’s not a best practice to just keep it as a string?

You are correct in pointing out that using JSON.parse() followed by JSON.stringify() in the following code sample would be superfluous if the answer is already a string. If the GET response is a valid JSON string, you can assign it directly to the HTML element without any additional parsing or stringifying.

In this situation, you can use req.responseText to assign the JSON string to the HTML element’s innerHTML attribute directly. Here’s a modified version of the code that removes the superfluous JSON.parse() and JSON.stringify() calls.

1 Like

@matelgouser2

Thank you very gracias!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.