Home > Enterprise >  How do get information from .json file
How do get information from .json file

Time:09-05

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"
    }
  ]
}
 
*/

CodePudding user response:

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.

CodePudding user response:

Did you try to access the members of memberList?

console.log(data2.memberList[0].age);
  • Related