0

I want to read the "name" and "tel" from data.json(json file) by using app.js(node js file)


This is data.json file

{
 "result": {
  "site": {
   "list": [
    {
     "name": "imready",
     "tel": "0123456789"
    },
    {
     "name": "hihello",
     "tel": "9876543210"
    }
   ]
  }
 }
}

This is the app.js file:

fs.readFile('data.json', 'utf8', function(err, data) {
console.log(data)});

I want to get: "name": "imready", "tel": "0123456789","name": "hihello", "tel": "9876543210".

How can do this?

Austin Mullins
  • 7,307
  • 2
  • 33
  • 48

2 Answers2

2

Use JSON.parse(data) inside your fs.readFile() callback. When reading your JSON from the file, you're just reading it as plain text, you need to explicitly generate the JS Object from the contents of data using JSON.parse().

fs.readFile('data.json', 'utf8', function(err, data) {
  var json = JSON.parse(data);

  // print { name: 'imready', tel: '0123456789' }
  console.log(json.list[0]);

  // print { name: 'hihello', tel: '9876543210' }
  console.log(json.list[1]);
});
peteb
  • 18,552
  • 9
  • 50
  • 62
  • *"...you're just reading it as plain text and not as JSON..."* JSON *is* plain text. He's reading it as JSON and needs to convert it to native JS objects. –  Mar 28 '16 at 18:22
  • 1
    @squint updated my answer – peteb Mar 28 '16 at 18:25
1

You can just require the json file and read from it as an object:

var obj = require('./data.json');
// now you can do:
console.log(obj.result.site.list[0].name) // => imready
cl3m
  • 2,791
  • 19
  • 21