nodejs read json file

To read a JSON file in Node.js, you can use the fs (File System) module to read the file, and then parse its contents using JSON.parse() to convert the JSON data into a JavaScript object. Here’s a step-by-step guide:

  1. Import the fs module:

    Start by importing the fs module at the top of your JavaScript file:

    1
    const fs = require('fs');
  2. Specify the file path:

    Define the path to your JSON file that you want to read:

    1
    const filePath = 'data.json'; // Replace with the actual file path
  3. Read the file content:

    Use the fs.readFile() function to read the contents of the JSON file. In this example, we’ll assume that the JSON file contains an array of objects:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
    console.error('Error reading the JSON file:', err);
    return;
    }

    try {
    const jsonData = JSON.parse(data);
    console.log('JSON data:', jsonData);
    } catch (parseError) {
    console.error('Error parsing the JSON data:', parseError);
    }
    });
    • The 'utf8' encoding is specified to ensure that the data is read as a text string.
    • Inside the callback function, we attempt to parse the JSON data using JSON.parse().
    • We handle errors during file reading and JSON parsing separately.
  4. Handling the JSON Data:

    You can now work with the jsonData variable, which contains the parsed JSON data as a JavaScript object. You can access and manipulate the data as needed in your application.

Here’s a complete example of reading a JSON file and working with the data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const fs = require('fs');
const filePath = 'data.json';

fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading the JSON file:', err);
return;
}

try {
const jsonData = JSON.parse(data);
console.log('JSON data:', jsonData);

// Access specific properties in the JSON object
console.log('First item:', jsonData[0]);
} catch (parseError) {
console.error('Error parsing the JSON data:', parseError);
}
});

Make sure to replace 'data.json' with the actual path to your JSON file. This example assumes that the JSON file is an array of objects, but you can adjust the parsing and handling to match your JSON structure.