Skip to content

Survey Exercise

GiovanniD_ edited this page Oct 22, 2020 · 7 revisions

About the Exercise

For this exersize we had to clean our own survey data. This data was collected at the start of the course, and was stored in a CSV file. This CSV file was cleaned and parsed into a JSON file by Jonah, Thanks for sharing!

Getting the Data

In my first try to log the data, I tried to open a local folder in the browser and used the fetch() method.

First attempt

fetch('../data/survey_id.json')
 .then((response) => {
  return response.json();
 })
 .then((obj) => {
  console.log(obj);
 })
 .catch((error) => {
  console.error('nope');
 });

This is the result i got from the console:

Cross origin requests are only supported for HTTP.
___

[Error] Fetch API cannot load [filepath] due to access control checks.

To fix this error I used the package live-server. For easy use I've added live-server to my start script.

The server will start by running the command: $ npm start in the terminal. The JSON data is now logged to the console.

Callbacks

For better readability of the code i rewrote the code adding some callbacks

const data = '../data/survey_id.json';
getData = (data) => {
 fetch(data)
  .then(status)
  .then(json)
  .then((data) => {
   console.log('Request succeeded with JSON response', data);
  })
  .catch((error) => {
   console.error('nope' + error);
  });
};
getData(data);
status = (response) => {
 if (response.status >= 200 && response.status < 300) {
  console.log(response);
  return Promise.resolve(response);
 } else {
  return Promise.reject(new Error(response.statusText));
 }
};
json = (response) => {
 return response.json();
};

Output

Request succeeded with JSON response `Objects`

Clone this wiki locally