Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use .find() on a JSON file to get a a string with a specific keyterm

I’m trying to use array.find() to get the first JSON string that contains amogus. I’ve tried to read the JSON file using fs then using JSON.parse() to make it readable. However, I can’t seem to get it to do what I want it to do.

JSON file:

{stuff: ["hosds29083", "amogus1208", "amogus1213"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

desired output: amogus1208

Thanks.

>Solution :

You can use the fs module in Node.js to read the JSON file, then use JSON.parse() to parse the file contents into a JavaScript object. Once you have the object, you can use the Array.prototype.find() method to find the first element in the "stuff" array that contains "amogus". Here’s an example:

const fs = require('fs');

fs.readFile('path/to/file.json', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  const json = JSON.parse(data);
  const result = json.stuff.find(item => item.includes('amogus'));
  console.log(result); // amogus1208
});

You should replace path/to/file.json with the actual path to the JSON file you want to read.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading