Search code examples
javascriptnode.jsjsonobjectreadfile

node fs.readfile reading json object property


I have the following json file.

{
  "nextId": 5,
  "notes": {
    "1": "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared.",
    "2": "Prototypal inheritance is how JavaScript objects delegate behavior.",
    "3": "In JavaScript, the value of `this` is determined when a function is called; not when it is defined.",
    "4": "A closure is formed when a function retains access to variables in its lexical scope."
  }
}

By using fs.readFile, I am trying to display only the properties like the follows. 1:The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared. 2:Prototypal inheritance is how JavaScript objects delegate behavior.

But my code shows the whole JSON file. My code is as follows:

const fs = require('fs');
const fileName = 'data.json';

fs.readFile(fileName, 'utf8', (err, data) => {
    if (err) throw err;

    const databases= JSON.parse(data);

    //databases.forEach(db=>{
    console.log(databases);
    //});
    //console.log(databases);
});

Solution

  • Well once you parsed the data now you have your object in memory and you can operate with it as you wish. You can extract the lines you tell about in the following way

    databases.notes["1"];
    databases.notes["2"];
    

    Note, here we are using numbers in string because you saved your messages as an object, where keys are strings. If you want to access that as an array you need to save that in the following way.

    {
      "nextId": 5,
      "notes": [
        "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared.",
        "Prototypal inheritance is how JavaScript objects delegate behavior.",
        "In JavaScript, the value of `this` is determined when a function is called; not when it is defined.",
        "A closure is formed when a function retains access to variables in its lexical scope."
      ]
    }
    

    Then you could do the following thing.

    databases.notes[0];
    databases.notes[1];
    

    And because it is an array now you could iterate over it.

    UPD: Based on comment.

    If you need to loop over keys and values then it can help.

    for (const [key, value] of Object.entries(databases.notes)) {
        console.log(key);
        console.log(value);
    }