Jay Syz Jay Syz - 1 year ago 86
JSON Question

Using Node js request module for JSON from API, can't access subcategories

I have a weird issue where I can successfully obtain data from an API source using Node js and the request module, but when I try to access a certain subcategory of the JSON data, the object becomes undefined.

Here's my code:

var request = require("request")

var url = "http://api.8coupons.com/v1/getcategory"

url: url,
json: true
}, function (error, response, body) {

if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
console.log(body.headers['categoryID']) // creates an error
console.log(body.categoryID) // creates an error

Here's my terminal output when I run the program:

node getJS.js
[ { categoryID: '1', category: 'Restaurants' },
{categoryID: '2', category: 'Entertainment' },
{ categoryID: '3', category: 'Beauty & Spa' },
{ categoryID: '4', category: 'Services' },
{ categoryID: '6', category: 'Shopping' },
{ categoryID: '7', category: 'Travel' } ]

> console.log(body.headers['categoryID'])
> ^
> TypeError: Cannot read property 'categoryID' of undefined
> at Request._callback (C:\Users\Jay\Desktop\Bill-e\getJS.js:12:33)
> at Request.self.callback (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:200:22)
> at emitTwo (events.js:87:13)
> at Request.emit (events.js:172:7)
> at Request.<anonymous> (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:1067:10)
> at emitOne (events.js:82:20)
> at Request.emit (events.js:169:7)
> at IncomingMessage.<anonymous> (C:\Users\Jay\Desktop\Bill-e\node_modules\request\request.js:988:12)
> at emitNone (events.js:72:20)
> at IncomingMessage.emit (events.js:166:7)

Answer Source

I think you have a little mistake here.

Your json data in the first level is an array so, to access the data, you need to pass the index you want to get from the array (directly or inside an iteration)



body.forEach(function(item) {

The headers is a property of the response param, to get the response headers from request (data like content-type, cookies)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download