1720453416

Practical examples of using data manipulation in JSON files in Node.js.


Manipulating data in JSON files with Node.js is a common task and can be done using native modules like fs (file system). Here are some practical examples for reading, writing, updating, and deleting data in JSON files. First, make sure you have Node.js installed. Create a new directory for your project and initialize a new Node.js project: ```bash mkdir json-manipulation cd json-manipulation npm init -y ``` To read data from a JSON file, you can use the **fs** module ```js const fs = require('fs'); fs.readFile('data.json', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const jsonData = JSON.parse(data); console.log(jsonData); }); ``` To write data to a JSON file, use **fs.writeFile** ```js const fs = require('fs'); const data = { name: "John", age: 30, job: "Developer" }; fs.writeFile('data.json', JSON.stringify(data, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing to the file:', err); return; } console.log('Data saved successfully!'); }); ``` To update data in a JSON file, you first read the file, modify the data, and then write it back to the file ```js const fs = require('fs'); fs.readFile('data.json', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const jsonData = JSON.parse(data); jsonData.age = 31; // Update the data as needed fs.writeFile('data.json', JSON.stringify(jsonData, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing to the file:', err); return; } console.log('Data updated successfully!'); }); }); ``` To delete specific data from a JSON file, you can remove the desired key from the JSON object and write it back to the file ```js const fs = require('fs'); fs.readFile('data.json', 'utf8', (err, data) => { if (err) { console.error('Error reading the file:', err); return; } const jsonData = JSON.parse(data); delete jsonData.job; // Remove the desired key fs.writeFile('data.json', JSON.stringify(jsonData, null, 2), 'utf8', (err) => { if (err) { console.error('Error writing to the file:', err); return; } console.log('Data updated successfully!'); }); }); ``` These examples demonstrate how to manipulate JSON files in Node.js for reading, writing, updating, and deleting data. You can expand these examples to handle more complex cases as needed in your project.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]