JavaScript Object Notation (JSON) is a file format in which we store data as a key-value pair. It is a standard and human-readable format that is used extensively. It can be converted easily to other file formats and parsed in different programming languages.
In this Answer, we'll learn how to parse a JSON file in Node.js.
Let's start with a simple JSON file:
[{"name": "Alice","age": 18,"city": "New York"},{"name": "Bob","age": 19,"city": "London"},{"name": "Charlie","age": 15,"city": "Tokyo"},{"name": "Eve","age": 20,"city": "Paris"},{"name": "Jane","age": 23,"city": "Sydney"},{"name": "Joe","age": 25,"city": "Berlin"}]
Now, we'll parse this JSON file.
Import the required modules for reading the file. The fs
module will do this job for us.
const fs = require('fs')
Store the path of the JSON file in a const
variable.
const path = 'pathToFile.json'
Next, read the file using the fs
module that we imported earlier.
fs.readFile(path, 'utf8', (err, data) => {// Read/modify file data here})
The readFile()
method of fs
module takes the file path path
, encoding to be used, which in this case is utf8
, and a callback function with two arguments: err
and data
.
In the callback function of the readfile()
method, we'll perform two operations:
Error handling
Data parsing
// inside the callback function// check for any errorsif (err) {console.error('Error while reading the file:', err)return}try {const data = JSON.parse(data);// output the parsed dataconsole.log(data);} catch (err) {console.error('Error while parsing JSON data:', err);}
We check for an error during file reading. If an error occurs, we simply log the error err
on the console and exit the callback function using the return
statement.
If there is no error, the try
block is executed, where we parse the JSON data using the JSON.parse()
method and output the data
on the console. If any error occurs while parsing the data, the catch
block logs that error err
on the console.Code
.
Here's the complete code. Click the "Run" button to execute the code.
const fs = require('fs')const path = 'sample.json'fs.readFile(path, 'utf8', (err, file) => {// check for any errorsif (err) {console.error('Error while reading the file:', err)return}try {const data = JSON.parse(file)// output the parsed dataconsole.log(data)} catch (err) {console.error('Error while parsing JSON data:', err)}})
We read the JSON file using the readfile()
method of the fs
module and parse the file using the JSON.parse()
method.
Free Resources