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! While you're at it, check out some resources Treehouse students have shared here.

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 Asynchronous Programming with JavaScript Understanding Promises Using Fetch

Farid Lavizadeh
Farid Lavizadeh
12,006 Points

Don't understand json() method.

Data in URL is already in JSON format. We used to parse it so it would convert to an object. Why are we using json() method to parse it back to JSON now? And if it is parsed to JSON how is being used as an Object?

2 Answers

The way I understand it is that whenever we receive data from a web server, the data is always a string. So we need to parse the data with JSON.parse() so the data becomes a JavaScript object. This object could be anything that can be represented by JSON β€” an object, an array, a string, a number... Once we have the data as a JS object, then we can do whatever we need with it.

Farid Lavizadeh
Farid Lavizadeh
12,006 Points

I understand that, but what is the difference between the following two methods; .json() for JSON.parse()? Does .json() convert a promise object to a regular object? Whereas JSON.parse converts JSON to a regular Object?

I had the same question.

Key Differences:

JSON.parse() = is a synchronous operation and works on a string, returning a JavaScript object.

json() = is asynchronous and works on a Response object, returning a promise that resolves to a JavaScript object (or array). It's a method available on the Response object returned by the fetch API in modern browsers.

It's worth noting that under the hood, json() likely uses JSON.parse() to accomplish its task, but it handles the promise mechanics and stream reading for you.