JSON (JavaScript Object Notation), is a standard for representing structured data based on JavaScript's object syntax. It is commonly used to transmit data in web apps via HTTP. For example, the HTTP fetch()
requests we have been using in this course have been returning Jello projects, users, and issues as JSON.
JSON supports the following primitive data types:
"Hello, World!"
42
or 3.14
true
null
And the following collection types:
[1, 2, 3]
{"key": "value"}
Because we already understand what JavaScript objects look like, understanding JSON is easy! JSON is just a stringified JavaScript object. The following is valid JSON data:
{
"movies": [
{
"id": 1,
"genre": "Action",
"title": "Iron Man",
"director": "Jon Favreau"
},
{
"id": 2,
"genre": "Action",
"title": "The Avengers",
"director": "Joss Whedon"
}
]
}
JavaScript provides us with some easy tools to help us work with JSON. After making an HTTP request with the fetch() API, we get a Response object. That response object offers us some methods that help us interact with the response. One such method is the .json()
method. The .json()
method takes the response stream returned by a fetch request and returns a promise that resolves into a JavaScript object parsed from the JSON body of the HTTP response!
const resp = await fetch(...)
const javascriptObjectResponse = await resp.json()
The .json()
method returns a promise that resolves to an object typed as any
. This means TypeScript doesn’t enforce any specific shape or structure for the returned data, leaving it up to you to handle the type appropriately.
If you know the shape of the data, you can explicitly set the return type — like we've done so far — or you can cast it to a specific type:
interface Project {
id: string;
title: string;
}
const response = await fetch("https://api.example.com/projects");
const projects = await response.json() as Project[];
Our getProjects
function is almost done, we just need to parse the response data as JSON and return it.
The result of this method is NOT JSON. It is the result of taking JSON data from the HTTP response body and parsing that input into a JavaScript Object.
Focus Editor
Alt+Shift+]
Next Tab
Alt+Shift+[
Become a member to Submit
Become a member to Run
Become a member to view solution