Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS returning garbage JSON

I am trying to write a simple piece of code using NodeJS to get the JSON back from the stack exchange API.

This is the API I am targetting- https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname=donal%20rafferty&site=stackoverflow

And here is my code:

var https = require('https'); //Use NodeJS https module

function getUserDataByName(userName, callback){

var stackOverflowUserURL = 'https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname='+encodeURIComponent(userName)+'&site=stackoverflow';

https.get(stackOverflowUserURL, function(response){
    console.log("headers: ", response.headers);
    if (response.statusCode == 200) {
        var jsonString = '';
        response.on('data', function (chunk) {
            jsonString += chunk;
        });
        response.on('end', function () {
            console.log((jsonString));
            callback(JSON.stringify(jsonString));
        });
    }
    else{
        //error
        console.log("Error");
    }
});
}

However when I run this the data always comes back in a state of garbage like text like the following:

\"\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0004\u0000uR�n�0\f��B���ږ\u0013�2\u0010�R�m�u\\u0018\\u0004ڢ\\u001d!��Jr=�ȿ�vS\\u0004\\u0005������H����C��7ր�Q�n��\u0012\u0014{g�\\"��]����+zV\u001f����(V��%a�n|�)QU�.O�\u000e\u0012�Ѹ\u0005��\u0003\u00130a\u0006B��S�Ө�����C^��bw�I\u000bC��b�\u0017e�\u0013�q�\\"D��lO`���@^\nq\u0017|���ի�������?pFz�i�R\u000f�,[�pu�{x�\b~k��LUV��\u0012\u00194�l\u000e�ڕ\rW��\u001c���*�\u001a�9�\u001e�Q+�Q��>���o��;a'\btI�b/�� \u0007�CK̲���\u0000�jۯ����\u0003g|�\u0003�\u0002\u0000\u0000\

I'm assuming there is something wrong with my encoding/decoding but I can't figure out what to do to fix this?

like image 927
Donal Rafferty Avatar asked Apr 20 '15 20:04

Donal Rafferty


1 Answers

You need to decode the response as it's gzipped

var https = require('https'); //Use NodeJS https module
var zlib = require("zlib");

function getUserDataByName(userName, callback){

var stackOverflowUserURL = 'https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&inname='+encodeURIComponent(userName)+'&site=stackoverflow';

https.get(stackOverflowUserURL, function(response){
    console.log("headers: ", response.headers);
    console.log(response.statusCode)
    if (response.statusCode == 200) {
        var gunzip = zlib.createGunzip();
        var jsonString = '';
        response.pipe(gunzip);
        gunzip.on('data', function (chunk) {
            jsonString += chunk;
        });
        gunzip.on('end', function () {
            console.log((jsonString));
            callback(JSON.stringify(jsonString));
        });
        gunzip.on('error', function (e) {
          console.log(e);
        });
    }
    else{
        //error
        console.log("Error");
    }
});
}
like image 113
Transcendence Avatar answered Oct 20 '22 17:10

Transcendence