Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js - I am having some trouble with JSON.parse()

Tags:

node.js

I have been playing around with the youtube API and node.js, so far I have been able to get a response from the API and console.log it onto the terminal.

When I try to get the response and use JSON.parse, I get a weird error:

Got response: 200

undefined:1
http://www.w3.or
^
SyntaxError: Unexpected token u
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/home/ubuntu/node_temp4/index.js:19:10)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1137:24)
    at TCP.onread (net.js:354:27)

This is my script:

var http = require("http");

var searchQuery = "cats";
var queryResponse;

var options = {
  host: 'gdata.youtube.com',
  path: "/feeds/api/videos?q=" + searchQuery + "&max-results=1&v=2&alt=json"
};

http.get(options, function(response) {
  console.log("Got response: " + response.statusCode);

  response.on('data', function(chunk){
    queryResponse += chunk;
  });

  response.on('end', function(){
    JSON.parse(queryResponse);
    console.log('end');
  });
}).end();
like image 259
user1215653 Avatar asked Feb 18 '12 10:02

user1215653


People also ask

Why does JSON parse not work?

parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code. If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands.

Is JSON parse blocking or not?

So yes it JSON. parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded. So the parsing would have to block the main thread at some point.

What error does JSON parse () throw when the string to parse is not valid JSON?

Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.


1 Answers

The variable queryResponse is set to undefined and you are doing queryResponse += chunk in the 'data' envent handler which means queryResponse = queryResponse + chunk so you get

undefined{"youtube":["Api", "response"]}

you can fix it by instantiating queryResponse as an empty string var queryResponse = ''

like image 137
LoG Avatar answered Oct 10 '22 01:10

LoG