Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Write a Basic Fetch Request

Amandeep Pasricha
Amandeep Pasricha
14,932 Points

Why are we parsing the data as JSON if JSON should technically be converted to a javascript object?

He wants the data as JSON, yet shouldn't it be parsed from JSON to javascript??

2 Answers

Eric M
Eric M
11,545 Points

Hi Amandeep,

JSON is a data format used by many languages. Most information is not parsed to a programming language but to a data structure that the programming language can interact with. It is possible for a web request to return all sorts of data. I might have an API endpoint mywebsite.com/hello that returns an mp3 file of me saying "hello". How is this communicated? All data is ultimately represented as bytes and a program needs to be told what sort of encoding those bytes use to represent their information. The encoding for JSON text and mp3 audio are of course different.

Here we know that the endpoint will return JSON, so we tell the program to interpret the data it receives as though it were JSON. If the data is not JSON, this will cause an error in the parser. If it is JSON our program will continue with whatever operations on the JSON we want to perform.

After the data is parsed as JSON we can turn it into an object, or extract one part of the JSON and store it is a string, or integer, or whatever is appropriate.



Guil misspeaks. The time I think you are referring to is at 04:30.

Simplified, response.json() does not parse "to JSON", but it parses the JSON from the response object to a JavaScript value, in this case a JavaScript object of no specific type, as can be verified with typeOf and instanceof. The data parameter in the next .then holds that JavaScript object. Because it is just an object, Guil can access its property with data.message.

Unsimplified, response.json() returns a promise with that object as its resolution value. A follow-up .then expects an onResolve-like handler (read: a function), and implicitly gives it the last resolution value as its argument. Therefore Guil can define an arrow function which receives that last resolution value in its data parameter. data is the JavaScript object, and can be accessed with simple JavaScript object syntax, like data.message returning a string.

MDN .json() method.