In an earlier article, I wrote about how to make a JSON request using XHR in vanilla JavaScript.

JSON is a widely used format for API response. JSON data is stored as key-value pairs similar to JavaScript object properties, separated by commas, curly braces, and square brackets.

When you make a JSON request using XHR, the response data can be retrieved from the responseText property on the XMLHttpRequest object:

const xhr = new XMLHttpRequest()

// ...

xhr.onload = () => {
  const data = xhr.responseText
}

Here is the full code for the JSON request:

const xhr = new XMLHttpRequest()

xhr.onload = () => {
  const data = xhr.responseText

  // log response
  console.log(data)
}

// create and send the request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts')
xhr.send()

The above code should work fine and log the response on the console. However, there is a slight problem. The xhr.responseText returns a string even though the response returned by the API is in JSON format.

There are multiple ways to solve this issue. Let us look at them.

Handle JSON response in Fetch API

Fetch API is a modern alternative to XHR for sending asynchronous HTTP requests in JavaScript. It also supports promises, another good thing for handling asynchronous requests in JavaScript.

Here is how you can use the Fetch API to retrieve a list of posts from JSONPlaceholder:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err))

The Fetch API is not supported by older browsers. So use this solution only if you don't need to support old browsers like Internet Explorer.

Using responseType property

Modern browsers allow you to use the responseType property on the XMLHttpRequest object to set the expected response format. XHR will automatically parse the response body as per the specified format. You can then access it through the response property, as shown in the following example:

const xhr = new XMLHttpRequest()

// specify response format
xhr.responseType = 'json'

xhr.onload = () => {
  const data = xhr.response

  // log response
  console.log(data)
}

// create and send the request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts')
xhr.send()

The responseType = 'json' is not supported by IE 11 and older versions.

Using JSON.parse() method

In old browsers, the best solution is to use the JSON.parse() method to convert the string returned by responseText to a JSON object:

const xhr = new XMLHttpRequest()

xhr.onload = () => {
  const data = JSON.parse(xhr.responseText)

  // log response
  console.log(data)
}

// create and send the request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts')
xhr.send()

The above code should work in any browser that supports XMLHttpRequest and JSON.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.