Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Fetch API to Access JSON

I am trying to use fetch api to bring back some data, however am unable to map it to the console once I have retrieved it.

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
}).then(function(response) {
  console.log(response)
  response.forEach(i => console.log(i.name));
}).catch(function(err) {
  console.log(`Error: ${err}` )
});

The error i get is

response.map is not a function

so I tried to parse the response,(ie var data=JSON.parse) which did not work, with the error

SyntaxError: Unexpected token o in JSON at position 1"

Interestingly, when doing the same thing with a XMLHttp request, I was required to parse it, so I would also be interested to know why the difference between these two methods of retrieving the data.

If anyone could point me in the right direction, I would be really grateful.

like image 724
matt-p Avatar asked Jun 06 '16 17:06

matt-p


People also ask

Does fetch parse JSON?

When the fetch is successful, we read and parse the data using json() , then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.

Can we fetch JSON file?

Any JSON data can be consumed from different sources like a local JSON file by fetching the data using an API call. After getting a response from the server, you need to render its value. You can use local JSON files to do an app config, such as API URL management based on a server environment like dev, QA, or prod.

What is JSON () in fetch?

json() returns a new Promise to you, so you need to create your object inside the then of the result of that function. If you return a Promise from a function, it will be fulfilled and will return the result of the fulfillment - in our case the object. fetch("https://jsonplaceholder.typicode.com/posts/1") .

How do I retrieve data from Fetch?

How do I return a response on Fetch? Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.


2 Answers

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.

fetch('http://jsonplaceholder.typicode.com/users', { 
  method: 'GET'
})
.then(function(response) { return response.json(); })
.then(function(json) {
  // use the json
});
like image 183
Steven Lambert Avatar answered Sep 20 '22 12:09

Steven Lambert


Understanding promises is key to using the fetch API.

At the time you're trying to parse your response and loop through it, the response is actually just a promise. In order to utilize the contents of the actual response from the request, you'll have to do some promise chaining.

fetch('http://jsonplaceholder.typicode.com/users').then(function(response) {
  // response.json() returns a promise, use the same .then syntax to work with the results
  response.json().then(function(users){
    // users is now our actual variable parsed from the json, so we can use it
    users.forEach(function(user){
      console.log(user.name)
    });
  });
}).catch(err => console.error(err));
like image 22
shamsup Avatar answered Sep 19 '22 12:09

shamsup