problem reading external NODEJS Json

Asked

Viewed 245 times

1

I have a problem to read an External Json but I can not identify, I have checked the json and it appears correct.

that would be Json https://the-evie.com/playerscript/pc/es/ililithz/043924923/ascxsa2342/23432

I checked and it’s correct, and before it worked and suddenly stopped

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (S:\SoulArts\DiscordBOT\run.js:2
    at emitOne (events.js:115:13)
    at IncomingMessage.emit (events.js:210:7)
    at IncomingMessage.Readable.read (_stream_readable.js:478:10)
    at flow (_stream_readable.js:849:34)
    at resume_ (_stream_readable.js:831:3)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

I read the json with that code

 var https = require('https');
        var optionsget = {
            host : the-evie.com,
            port : 443,
            path : '/playerscript/pc/es/ililithz/043924923/ascxsa2342/23432r", 
            method : 'GET'
        };

    //tenta ler json recebido pelo HTTP e transforma em strings
    var reqGet = https.request(optionsget, function(res) {
    console.log(">> statusCode: ", res.statusCode);
    res.on('data', function(d) {
        var obj = JSON.parse(d); 
        var checkresponse = obj.response_check;
        var username = obj.username;
        var region = obj.region;
        var level = obj.level;
        var max_playtime = obj.max_total_playtime;
        var main_champ = obj.main_champion;
        var comp_tier  = obj.comp_tier;
        var comp_point = obj.comp_point;
        var casualwin = obj.casual_total_wins;
        var casuallos = obj.casual_total_losses;
        var casualkda = obj.normal_kda;
        var compwin = obj.comp_win;
        var complos = obj.comp_loss;
        var compkda = obj.rank_kda;
        var winrateOne = obj.normal_winrate;
        var winrateTwo = obj.rank_winrate;
        var casualChamp = obj.casual_top_Champion;

1 answer

1


Treat that answer as a stream and creates a function that processes the pieces that arrive until the text is complete.

It could be something like this, that I tested here:

const https = require('https');
const url = 'https://the-evie.com/playerscript/pc/es/ililithz/043924923/ascxsa2342/23432';

function getJSON(url){
    return new Promise((resolve, reject) => {
        let json = '';
        https
            .get(url, res => {
                res.on('data', d => (json += d));
                res.on('end', () => resolve(JSON.parse(json)));
            })
            .on('error', reject);
    });
}

getJSON(url).then(obj => {
  console.log(obj.main_champion); // Evie
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.