Reputation: 769
I have the following code inside a get request in NodeJS
response.on('data', function (chunk) {
console.log(chunk);
JSON.parse(chunk);
console.log("ch"+chunk.product.productId);
responseData+=chunk;
});
The first console.log prints the entire response, which is a JSON in form of a string:
{"product":[{"defaultProductUrl":"http:\/\/www.zappos.com\/product\/7306789","defaultImageUrl":"http:\/\/www.zappos.com\/images\/z\/2\/1\/3\/2\/5\/4\/2132548-p-DETAILED.jpg","productId":"7306789","productName":"Pro Short","brandId":"1630","brandName":"CW-X"}],"statusCode":"200"}
The second one however throws an error:
console.log("ch"+chunk.product.productId);
TypeError: Cannot read property 'productId' of undefined
at IncomingMessage.<anonymous> (c:\Users\Udai\Desktop\Zappos\server.js:78:38)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:746:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at IncomingMessage.Readable.push (_stream_readable.js:127:10)
at HTTPParser.parserOnBody [as onBody] (http.js:141:22)
at Socket.socketOnData [as ondata] (http.js:1584:20)
Any ideas on what's going on?
Upvotes: 1
Views: 1694
Reputation: 123513
There can be, and often are, more than a single chunk
of 'data'
in a readable stream. You'll want to make sure you have all of them (even if there is only 1) and perform processing once it's come to an 'end'
.
var body = '';
response.on('data', function (chunk) {
body += chunk.toString();
});
response.on('end', function () {
// ...
});
You also need to store the result of JSON.parse()
as it won't alter its argument.
var data = JSON.parse(body);
Then, from the [...]
in the JSON, data.product
will be an Array
of Object
s. So, you'll have to access an index of it to retrieve a productId
.
console.log(data.product[0].productId);
Upvotes: 2
Reputation: 191779
You need to accumulate all of the data before you can run JSON.parse
on it. That is, keep accumulating the chunks in responseData += chunk
, then run JSON.parse
. Otherwise, you could run JSON.parse
on a string like: {"prop":
followed by another chunk: "value"}
. Neither of those are valid JSON:
response.on("end", function () {
console.log(JSON.parse(responseData));
});
Upvotes: 2