Reputation: 221
In my code, when I attempt to load the contents of a json file and then log the Name
attribute of each of the objects within the json object, I'm receiving nothing being logged
Here's my code, all help is appreciated, thank you.
var options = {
host: 'www.roblox.com',
port: 80,
path: '/catalog/json?resultsperpage=42',
method: 'GET'
};
http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
chunk = JSON.parse(chunk);
for (var x in chunk) {
console.log(chunk[x]['Name']);
}
//console.log(chunk);
});
}).end();
Upvotes: 0
Views: 48
Reputation: 268
The reason your JSON parse didn't work is because you called it too early during the 'data' event. It was only sending the chunks of response at that point, and you didn't have the full response (which is text that should be valid JSON). Do your work on the 'end' event.
var http = require('http');
var options = {
'host': 'www.roblox.com',
'port': 80,
'path': '/catalog/json?resultsperpage=42',
'method': 'GET',
'content-type': 'application/json'
};
http.request(options, function(res) {
var response_string = "";
res.setEncoding('utf8');
res.on('data', function (chunk) {
response_string += chunk;
});
res.on('end', function() {
var chunk = JSON.parse(response_string);
for (var x in chunk) {
console.log(chunk[x]['Name']);
}
console.log(chunk);
});
}).end();
Upvotes: 1
Reputation: 1
Full working version
var http = require('http');
var options = {
host: 'www.roblox.com',
port: 80,
path: '/catalog/json?resultsperpage=42',
method: 'GET',
headers: { // note how you add headers
'content-type': 'application/json'
}
};
http.request(options, function(res) {
res.setEncoding('utf8');
var result = ""; // result will be built up into this
res.on('data', function (chunk) {
result += chunk; // add the chunk to the result
}).on('end', function() { // now parse it and do things
var json = JSON.parse(result);
for (var x in json) {
console.log(json[x]['Name']);
}
//console.log(chunk);
});
}).end();
Upvotes: 1
Reputation: 20359
When you make a request in Node.js, there is no guarantee that all of the data will come in a single chunk, so you need to build up your result out of the request chunks until you are sure you have all of them (i.e. the end
event). Try the following code instead:
var options = {
host: 'www.roblox.com',
port: 80,
path: '/catalog/json?resultsperpage=42',
method: 'GET'
};
http.request(options, function(res) {
res.setEncoding('utf8');
var result = "";
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function() {
result = JSON.parse(result);
for (var x in result) {
console.log(result[x]['Name']);
}
console.log(result);
});
}).end();
For more information on how to make HTTP requests in Node.js, please see this article.
Upvotes: 3