Make remote json into string

Asked

Viewed 17 times

2

As it is possible to return the value of a remote json and read as string, example when I get the json it prints the whole result as in the image below. Todo Resultado do json code below:

var https = require('https');
    var optionsget = {
        host : 'the-evie.com',
        port : 443,
        path : '/playerscript/pc/Droust', 
        method : 'GET'
    };
    console.info('Options prepared:');
    console.info(optionsget);
    console.info('Do the GET call');

var reqGet = https.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);
    res.on('data', function(d) {
        console.info('GET result:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });
});
reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

what I wanted was to make this filtered as for example the username, was able to receive the value by key, ie key username value Droust.

1 answer

2


Convert Json to an object.

var obj = JSON.parse(text);

Then just take the value you want from this object.

var user = obj.username;

This way your user variable will receive the Droust value.

Give a read here too, it might help you: https://www.w3schools.com/js/js_json.asp

  • how it is possible to use it outside the function, in another function?

  • I didn’t quite understand your question. Use what outside the function?

  • the variable it exists inside the var reqGet = https.request(optionsget, Function(res) { }); however I cannot use it outside

  • I think I get it now. You can declare var obj outside the context of its functions. And within your function you make the obj variable receive your text and be converted to object. And then you can use it wherever you want in your code.

  • @Samuelhenriquerizzon (cc @Carloseduardo) se https.request is asynchronous that’s not true!

Browser other questions tagged

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