Working with JSON and APIs
How Node.js programs send and receive data over the internet
- turn a JavaScript value into JSON text with
JSON.stringify, and back withJSON.parse, - explain what a REST API is in plain words,
- send a JSON response from Express with
res.json(), - call another API from Node with
fetchand read its JSON.
1. What is JSON?
JSON stands for JavaScript Object Notation. It is just text that describes data using curly braces, square brackets, numbers, and strings in double quotes. Because it is plain text, it can be saved to a file or sent across the internet, and almost every programming language can read it.
A JavaScript object lives inside your program's memory. JSON is the text version of that data. Two built-in tools move between them:
JSON.stringify(value)- turns a JS value into a JSON string (to send or save it).JSON.parse(text)- turns a JSON string back into a JS value (to use it).
const user = { name: "Ada", age: 36, likes: ["math", "code"] };
const json = JSON.stringify(user);
console.log(json);
console.log(typeof json);
// Output:
// {"name":"Ada","age":36,"likes":["math","code"]}
// string
Notice the result is a string. Every key and every text value is wrapped in double quotes — that is a strict rule of JSON. To go the other way, use JSON.parse:
const text = '{"name":"Ada","age":36}';
const obj = JSON.parse(text);
console.log(obj.name);
console.log(obj.age + 1);
// Output:
// Ada
// 37
parse, obj.age is a real number, so obj.age + 1 gives 37, not "361".