In a node.js server, I am parsing a JSON response from a database, but while accessing the object it returns undefined.
How do I access the object and get my desired value for the particular key?
Request code
var jsonpass = {};
let url = 'http://localhost:3003/customer/2';
let gID = req.params.id;
request.get(url, (error, reponse, body) => {
jsonpass = JSON.parse(body);
console.log('body', body, '\njsonpass ', jsonpass);
if (error) {
console.log(error);
}
});
Output
body {"message":"get single data","data":[{"CUSTID":2,"NAME":"Harsh Mundhada","EMAIL":"HARSH","DESCRIPTION":"HARSH","PHONENUMBER":"+917378456555","FREQUENCY":"harsh","DAYNMONTH":"HARSH","INVOICENUMBER":"HARSH","DISTINCTDATES":null}]}
jsonpass {
message: 'get single data',
data: [
{
CUSTID: 2,
NAME: 'Harsh Mundhada',
EMAIL: 'HARSH',
DESCRIPTION: 'HARSH',
PHONENUMBER: '+917378456555',
FREQUENCY: 'harsh',
DAYNMONTH: 'HARSH',
INVOICENUMBER: 'HARSH',
DISTINCTDATES: null
}
]
}
when I am trying to print the JSON object, I am getting the result as undefined
console.log('\nmessage-\n',jsonpass["message"]);
console.log('\nmessage2-\n',jsonpass.message);
console.log('\nmessage3-\n',String(jsonpass.message));
Output
message-
undefined
message2-
undefined
message3-
undefined
Why is it giving me undefined and how do I solve it?