0

JSON data : {

"8500500561":{
         "food":"400",
         "cloth":"44",
         "travel":"44"
         }

}

I'll get the key value to access the JSON data dynamically

Node.js file :

 const fs  = requrie('fs');
 let rawdata = fs.readFileSync('data.json');
 let mydata = JSON.parse(rawdata);
 mob = '8500500561';
 console.log(mydata.mob.food);

but when I use this I'm getting an error : TypeError: Cannot read property 'food' of undefined

Akhil Pilli
  • 276
  • 5
  • 7
  • Possible duplicate of [Parsing values from a JSON file?](https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file) – Alejandro Jan 16 '19 at 17:18
  • 3
    By writing `mydata.mob` you are looking for the key `mob` in the object `mydata`. What you should be doing is `mydata[mob]`. – Azami Jan 16 '19 at 17:19
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Kevin B Jan 16 '19 at 19:05

1 Answers1

1

MadWard is correct in his comment. You would to structure it like this. You do have some typos in your example you are probably aware of but just pointing them out in case.

const fs  = requrie('fs'); //should be require
let rawdata = fs.readFileSync('data.json');
let mydata = JSON.parse(rawdata);
mob = '8500500561'; //850050051 in dataFile
console.log(mydata[mob].food);
DublinDev
  • 2,318
  • 2
  • 8
  • 31