Welcome back to CodeYourCraft! Today, we're diving into the world of response formats, focusing on JSON (JavaScript Object Notation). This tutorial is designed for both beginners and intermediates, so let's get started!
JSON is a lightweight data interchange format that's easy for humans to read and write and easy for machines to parse and generate. It's a text format that's widely used for asynchronous browser/server communication, including with APIs (Application Programming Interfaces).
JSON is a popular choice because it's:
JSON data consists of key-value pairs, similar to JavaScript objects, and is enclosed in curly braces {}. Here's a simple JSON example:
{
"name": "John",
"age": 30,
"city": "New York"
}In Node.js, you can work with JSON data using the built-in http and url modules. Here's an example of creating a JSON response using the http module:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ name: 'John', age: 30, city: 'New York' }));
});
server.listen(3000, () => console.log('Server running on port 3000'));In this example, we create a simple HTTP server that listens on port 3000. When a request is made, the server responds with a JSON object containing the keys name, age, and city.
To parse JSON in Node.js, you can use the built-in JSON.parse() function. Here's an example:
const data = '{"name": "John", "age": 30, "city": "New York"}';
const user = JSON.parse(data);
console.log(user.name); // JohnIn this example, we have a JSON string that we parse into a JavaScript object using JSON.parse(). Then, we access the name property of the object and log it to the console.
What is JSON?
That's it for today! In the next lesson, we'll explore more about working with JSON in Node.js, including reading and writing files. Until then, happy coding! 🎉