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

How do get information from .json file

I have this index.js and it’s logging the whole .json file. I want to log the age (21). How do I do that?

const fs = require('fs');
 
async function doSomething() {
  const data = fs.readFileSync("./apple.json")
  const data2 = await JSON.parse(data)
  console.log(JSON.stringify(data2, null, 2))
}
doSomething()

and a side question:
Is there a way to avoid using fs to read files?

/*
apple.json

{
   "memberList":[
      {
         "age":"21",
         "name":"Jom"
      }
   ]
}
*/
/*
Output:
 
{
  "memberList": [
    {
      "age": "21",
      "name": "Jom"
    }
  ]
}
 
*/

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

>Solution :

Your first question is quite obvious and this answer will not address it. Regarding your second question, yes. Using commonjs you just have to require the file. Like this:

const data = require('./apple.json');

If you are using ES6 modules, then you have to addd a assert statement. Like this:

import data from './apple.json' assert {type: 'json'};

If this answered your question, then you can mark it as correct.

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