Reputation:
I'm trying to access a JSON object but I'm getting errors while accessing the object. Could you please go through the code and let me know the mistake I'm making.
I'm writing 2 different cases to give a better understanding about my problem
Here's the JSON data:
Case 1:
If I just try to access the company_base object, I'm getting the Undefined value
if(!error && response.statusCode == 200){
console.log("Insurance name is.....");
var parsedData = JSON.parse(body);
console.log(parsedData["company_base"]);
}
Result: Insurance name is..... undefined
CASE 2:
I'm attaching 2 images. One contains the JSON text and the other contains the error I'm getting while trying to access the JSON object.
//This is the Code I'm using to access the object
if(!error && response.statusCode == 200){
console.log("Insurance name is.....");
var parsedData = JSON.parse(body);
console.log(parsedData["company_base"][""business_type"]);
}
Insurance name is..... C:\Users\Ebbie\Desktop\Misc\mean\udemy\the web developer bootcamp\IntroToApis\CSG\app.js:37 console.log(parsedData["company_base"]["business_type"]); ^
TypeError: Cannot read property 'business_type' of undefined at Request._callback (C:\Users\Ebbie\Desktop\Misc\mean\udemy\the web developer bootcamp\IntroToApis\CSG\app.js:37:47) at Request.self.callback (C:\Users\Ebbie\Desktop\Misc\mean\udemy\the web developer bootcamp\IntroToApis\CSG\node_modules\request\request.js:186:22) at emitTwo (events.js:106:13) at Request.emit (events.js:191:7) at Request. (C:\Users\Ebbie\Desktop\Misc\mean\udemy\the web developer bootcamp\IntroToApis\CSG\node_modules\request\request.js:1081:10) at emitOne (events.js:96:13) at Request.emit (events.js:188:7) at IncomingMessage. (C:\Users\Ebbie\Desktop\Misc\mean\udemy\the web developer bootcamp\IntroToApis\CSG\node_modules\request\request.js:1001:12) at IncomingMessage.g (events.js:291:16) at emitNone (events.js:91:20)
Upvotes: 1
Views: 10239
Reputation: 11786
Could you please go through the code and let me know the mistake I'm making.
You are getting undefined
because parsedData
is an array of one element. Notice [
at the beginning of the json data. Instead of using parsedData["company_base"]
to get value, iterate over it.
'use strict';
let _ = require('lodash');
if (!error && response.statusCode == 200) {
let insuranceCompanies = JSON.parse(body);
_.each(insuranceCompanies, (company) => {
let companyBase = company.company_base;
console.log('Insurance name is.....', companyBase.business_type);
});
}
Since company_base
and business_type
are static keys, I am using dotted notation to its access value.
Upvotes: 0
Reputation: 5606
It's returning an array of objects. parsedData["company_base"] is trying to access the company_base key on the array.
You would want something like this:
parsedData[0]["company_base"]
And..
parsedData[0]["company_base"][""business_type"]
Upvotes: 1