How To Parse JSON In Node.js
In this tutorial, I will show you some methods to parse JSON in Node.js. So, Let’s start:
Note: This article will help you too: Parse JSON In Node.js From External URL
Table of Contents
- Create a JS File
- Parse From Variable
- Using stringify() Function
- Async-Await Function
- Asynchronous Function
- Using FileSystem
Step 1 : Create a JS File
First, we have to create a JavaScript file called “server.js“. Then go to the directory using CMD. Open the newly created server.js file using an editor. We will test all methods in the file.
So, the environment is ready. Now let’s see the ways.
Step 2 : Parse From Variable
This is a basic way to parse JSON. You can use this in normal JS. Open server.js file and paste this code:
// json data
var jsonData = '{"users":[{"name":"Name 1"},{"name":"Name 2"}]}';
// parse json
var jsonParsed = JSON.parse(jsonData);
// access elements
console.log(jsonParsed.users[0].name);
Run the file:
node server
The output will look like:
Step 3 : Using stringify() Function
JSON.stringify() function converts Javascript Object into the String and
JSON.parse() function converts String into Javascript object.
Again open the server.js file. Clear the file and paste this code:
let data = require('./users.json');
let string = JSON.stringify(data);
console.log(string);
Run the file to see the output.
Step 4 : Async-Await Function
We can use async-await to parse JSON. Here’s an example:
async function parseJsonAsyncFunc(jsonString) {
const obj = await JSON.parse(jsonString);
console.log(obj.users[0].name);
}
let data = '{"users":[{"name":"Name 1"},{"name":"Name 2"}]}';
parseJsonAsyncFunc(data);
Step 5 : Asynchronous Function
Let’s see an example using asynchronous function:
const parseJsonAsyncFunc = jsonString => {
return new Promise(resolve => {
setTimeout(() => {
resolve(JSON.parse(jsonString));
});
});
}
let data = '{"users":[{"name":"Name 1"},{"name":"Name 2"}]}';
parseJsonAsyncFunc(data).then(jsonData => console.log(jsonData.users[0].name));
Step 6 : Using FileSystem
In the root directory of your project, create a file called “users.json”. Then paste this demo json data into the file:
{
"users":[
{
"username":"name1",
"name":"Name 1",
"email": "[email protected]"
},
{
"username":"name2",
"name":"Name 2",
"email": "[email protected]"
},
{
"username":"name3",
"name":"Name 3",
"email": "[email protected]"
}
]
}
We will read the users.json file using two methods:
- readFileSync()
- readFile()
The readFileSync
function reads data from a file in a synchronous manner. Let’s see an example of readFileSync() method:
const fs = require('fs');
const fileContents = fs.readFileSync('./users.json', 'utf8');
try {
const data = JSON.parse(fileContents)
console.log(data);
} catch(err) {
console.error(err);
}
See and example of readFile() method:
const fs = require('fs');
fs.readFile('./users.json', 'utf8', (err, fileContents) => {
if (err) {
console.error(err)
return;
}
try {
const data = JSON.parse(fileContents)
console.log(data);
} catch(err) {
console.error(err);
}
})
I hope this article helped you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.