Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Working with JSON Data in Node.js

Working with JSON Data in Node.js

Working with JSON data in Node.js is a common task, especially when dealing with APIs or reading/writing configuration files. Node.js provides built-in modules to handle JSON data. Here's an overview of how to work with JSON data in Node.js:

Parsing JSON:

1. Parsing JSON from a String:

To parse JSON data from a string, you can use JSON.parse():

const jsonString = '{"name": "John Doe", "age": 30}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Output: John Doe
 

2. Reading JSON from a File:

If you have a JSON file, you can read and parse it using the fs module:

const fs = require('fs');

fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  const parsedData = JSON.parse(data);
  console.log(parsedData);
});
 

Creating JSON:

1. Creating JSON from JavaScript Objects:

You can create a JavaScript object and convert it to JSON using JSON.stringify():

const data = {
  name: 'John Doe',
  age: 30
};

const jsonString = JSON.stringify(data);
console.log(jsonString); // Output: {"name":"John Doe","age":30}
 

Modifying JSON:

1. Modifying JSON Data:

To modify JSON data, you first need to parse it, make the necessary changes, and then stringify it back:

const jsonString = '{"name": "John Doe", "age": 30}';
const parsedData = JSON.parse(jsonString);

// Modify data
parsedData.age = 31;

const updatedJsonString = JSON.stringify(parsedData);
console.log(updatedJsonString); // Output: {"name":"John Doe","age":31}
 

2. Writing JSON to a File:

To save JSON data to a file, you can use the fs.writeFile() function:

 
const fs = require('fs');

const data = {
  name: 'John Doe',
  age: 31
};

const jsonString = JSON.stringify(data);

fs.writeFile('data.json', jsonString, 'utf8', (err) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log('Data written to file');
});
 

Handling Errors:

When working with JSON data, it's important to handle potential errors, especially when parsing data from external sources or reading files.

try {
  const parsedData = JSON.parse(jsonString);
  console.log(parsedData);
} catch (error) {
  console.error('Error parsing JSON:', error);
}