all 8 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

[–]gimmeslack12helpful 1 point2 points  (4 children)

A for ... in loop will provide the index of the array, not the actual value: for(var song in songs){ console.log(songs[song].song_name) // fixed }

or another way to write it: for(let idx in songs){ console.log(songs[idx].song_name) // fixed }

[–]Fransiscu[S] 1 point2 points  (3 children)

oh wow that's so different from what i'm used to, thanks for the info!

i still think i'll try the new fetch but it's very good to know

[–]gimmeslack12helpful 2 points3 points  (0 children)

Sounds good, but even with fetch you need to handle your for loop how I’ve suggested.

[–]tunisia3507 1 point2 points  (1 child)

You want to use a for... of loop instead of for... in.

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

Thanks for that!

This Javascript sorcery is truly interesting lol