0

I am trying to get json values using nodejs but not working.I have searched some question in stackoverflow related this but always I am getting [Object Object] like this.I do not know Why I am getting like this.Anyone can resolve this issue?

file.json:

{
    "scripts": {
        "mr": "place",
        "kg": "time",
        "bh": "sec"
    }
}

extension.js:

var fs = require("fs");
var file = JSON.parse(fs.readFileSync("c:\\xampp\\htdocs\\projects\\file.json", "utf8"));
console.log(file);

This is not duplicate. I have tried many ways but not working. Note:I am using this code inside my visual studio code extension.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Apple Orange
  • 646
  • 5
  • 12
  • 27
  • 1
    When you `JSON.parse` the file, it turns it into a javascript object. By default those get logged as [Object object]. You can try logging a specific thing (e.g. `console.log(file.scripts.mr);` So you are probably correctly parsing the file data. – Joe Aug 25 '19 at 20:30
  • Getting undefined – Apple Orange Aug 25 '19 at 20:39

3 Answers3

2

In node, you can import JSON like a JavaScript file

const file = require('./file.json')
console.log(file)

See is there a require for json in node.js for more info

jeff-v
  • 21
  • 5
1
const data = require("./file.json")
console.log(data.scripts)
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
0

Try this one out it is simple.

const fs = require('fs');
const paht = require('path');
console.log(paht.join(__dirname,'../file.json'));
let file = JSON.parse(fs.readFileSync(paht.join(__dirname,'../file.json'), "utf8"));

__dirname gives you the directory of your current file, I used path.join to make sure I can go further. I put the json file in upper directory in my case

Syed Afzal
  • 150
  • 1
  • 8