Artium Artium - 3 years ago 278
HTTP Question

Making HTTP request and parsing the result as JSON

I want to download a JSON and parse it. I tried the following approach:

var request = require('request');
var url = ""
var result = request(url , function(error, response, body) {

> Fin
SyntaxError: Unexpected token
at Object.parse (native)
at Request._callback (repl:1:81)
at Request.self.callback (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:186:22)
at emitTwo (events.js:87:13)
at Request.emit (events.js:172:7)
at Request.<anonymous> (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:1163:10)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
at IncomingMessage.<anonymous> (/home/artium/Projects/nlihack-team-m7/node_modules/request/request.js:1085:12)
at IncomingMessage.g (events.js:260:16)

I am able to log the JSON string retrieved in the body, it looks ok to me, so I guess I am doing the parsing wrong.


The first characters of the body looks like this:

> body.substring(1,250)
'{"@context":"",\n"@id": "",\n"@type":"sc:Collection",\n"label":"Dan Hadani Collection", \n"attribution":[{"@value":"The National Library of Israel","@language'

Answer Source

Tested & working after specifying encoding:


It seems that the specific url you are requesting does not specificity it's encoding in the response header, so we have to manually set it like so:

 request(u ,{encoding:'utf8'}, 
   function(error, response, body) { console.log("Fin");  JSON.parse(body)  })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download