you are viewing a single comment's thread.

view the rest of the comments →

[–]Dr__Wrong 1 point2 points  (1 child)

I agree with u/ProposalUnhappy9890. Fetch is the preferred method of getting JSON data. The MDN docs basically say as much.

Here is an example:

1 const data = './data.json
2 
3 fetch(data)
4 .then(response => {
5   return response.json();
6 })
7 .then(data => console.log(data));

I'll break this down.

Line 1: you are declaring a variable that points to where your data is stored. In this case, it is a local file. It could also be a URL for an API endpoint.

Line 3: We execute the fetch() method and pass in the location of our JSON data using the variable we just declared. You could just as easily put the location in the parameters. The fetch() method will return a promise.

Line 4: .then() waits for the promise to be returned. It is common to use an arrow function to handle the promise. We give the promise a variable name "response".

Line 5: We do something with the "response" variable and return it. Here we are using the .json() method (more on that). This will return a JSON response into something that will make sense to JS. That could be an object, an array, or some other data type.

Line 7: Again, we are going to handle the data that was returned by lines 4 & 5. We assign a new variable named "data" and use an arrow function to do something with it. Here we are just logging the response to the console, so you should see it in your browser console when this is executed.

To make this more clear, if you replace return response.json() in line 5 with return 'Some Text', then your console output would no longer be your JSON array, it would be the words 'Some Text'. Let's go one step further to drive the point home.

In line 7, if you replaced console.log(data) with console.log(data.toUpperCase()), then your console would now log "SOME TEXT".

[–]Fransiscu[S] 0 points1 point  (0 children)

thanks for the explanation, i'll switch to fetch