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 names array
  • Checks if the readable property is true
  • 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.

Updated on: 2026-03-15T23:18:59+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements