node.js - NodeJS get request. JSON.parse: unexpected token -
i'm writing function in nodejs hits url , retrieves json. i'm getting error in json.parse: unexpected token.
in json validators string passing test when copy browser , paste text field, when paste url parser json show me invalid message.
i guess encoding of response, can;t figure out is. here if function example url.
function getjsonfromurl(url, callback) { url = 'http://steamcommunity.com/id/coveirao/inventory/json/730/2/'; http.get( url , function (res) { // explicitly treat incoming data utf8 (avoids issues multi-byte chars) res.setencoding('utf8'); // incrementally capture incoming response body var body = ''; res.on('data', function (d) { body += d; }); // whatever want response once it's done res.on('end', function () { console.log(body.stringfy()); try { var parsed = json.parse(body); } catch (err) { console.error('unable parse response json', err); return callback(err, null); } // pass relevant data callback console.log(parsed); callback(null, parsed); }); }).on('error', function (err) { // handle errors request console.error('error request:', err.message); callback(err, null); }); }
can me, please?
thanks in advance help.
concatenating response string might have issues encoding e.g. if buffer of every chunk converted string partial utf-8 encodings @ beginning or end. i'd advise concatenate buffer first:
var body = new buffer( 0 ); res.on('data', function (d) { body = buffer.concat( [ body, d ] ); });
of course might explicitly convert buffer string on behalf rather relying on json.parse() doing implicitly. might essential in case of using unusual encoding.
res.on('end', function () { try { var parsed = json.parse(body.tostring("utf8")); } catch (err) { console.error('unable parse response json', err); return callback(err, null); } ...
aside content delivered given url seems pretty valid json.
Comments
Post a Comment