Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to selectively retrieve value from json output JavaScript
We have the following data inside a JSON file data.json:
data.json
{
"names": [{
"name": "Ramesh",
"readable": true
}, {
"name": "Suresh",
"readable": false
}, {
"name": "Mahesh",
"readable": true
}, {
"name": "Gourav",
"readable": true
}, {
"name": "Mike",
"readable": false
}]
}
Our job is to create a function parseData that takes the path to this file as an argument, reads this JSON file, and returns a filtered array containing only objects where the readable property is true.
Using require() Method
In Node.js, we can use the require() method to directly import JSON files. The data is automatically parsed, so no need for JSON.parse():
const path = "./data.json";
const parseData = (path) => {
const data = require(path);
// Data is already parsed when using require()
return data.names.filter(el => el.readable);
}
const results = parseData(path);
console.log(results);
[
{ name: 'Ramesh', readable: true },
{ name: 'Mahesh', readable: true },
{ name: 'Gourav', readable: true }
]
Using File System and JSON.parse()
Alternatively, you can read the file using the file system module and manually parse the JSON:
const fs = require('fs');
const parseDataWithFS = (filePath) => {
const rawData = fs.readFileSync(filePath, 'utf8');
const data = JSON.parse(rawData);
return data.names.filter(el => el.readable);
}
// Simulating with JSON string for demo
const jsonString = `{
"names": [
{"name": "Ramesh", "readable": true},
{"name": "Suresh", "readable": false},
{"name": "Mahesh", "readable": true}
]
}`;
const data = JSON.parse(jsonString);
const filteredResults = data.names.filter(el => el.readable);
console.log(filteredResults);
[
{ name: 'Ramesh', readable: true },
{ name: 'Mahesh', readable: true }
]
How It Works
The solution uses the filter() method to create a new array containing only elements that pass the test function. In this case, we test if el.readable is true. The filter method:
- Iterates through each object in the
namesarray - Checks if the
readableproperty istrue - Returns a new array with only matching objects
Conclusion
Use require() for simple JSON file imports in Node.js, or combine fs.readFileSync() with JSON.parse() for more control. The filter() method efficiently selects objects based on specific criteria.
