0

Ok, like the title i don't know i can do this. I have to open a url where there is json code and store it in a variable. I tried this way that I found here:

module.exports.run = async (bot, message, args) => {
  let url = "my link"
  snekfetch.get(url).then(r => 
  message.channel.send(decodeURIComponent(r.body)));
}

But this doesn't work.

Now I tried this code:

const fetch = require('node-fetch');
fetch(userUrl)
  .then(res => res.json())
  .then(json => console.log(json));
};

And I got this: console log

How can I i take those object and store them value in an variable?

I've solved it: The function

async function takeXpVerification(userUrl){
    return await fetch(userUrl)
    .then(res => res.json())
}

Where i call it for get the value

getAfterCurrentXp = await takeXpVerification(userUrl);
getAfterCurrentXp = getAfterCurrentXp["profile"]["experience"];
  • You already have the object in the `json` variable. I guess what you actually want is to return the result of your request synchronously which is not possible (the way I assume you want to to work) – Seblor Oct 02 '19 at 09:07
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Seblor Oct 02 '19 at 09:08
  • I want to take the value of one of this json in a var – Andrea Fiore Oct 02 '19 at 09:30
  • I don't understand. Do you want a subset of the json ? In your code, the `json` variable that you are logging is the variable that has the value you are asking for. – Seblor Oct 02 '19 at 09:49
  • I want to put in a variable this value experience: 621091, and how can i access to the other object? – Andrea Fiore Oct 02 '19 at 10:56

1 Answers1

0

First of all, snekfetch package is deprecated, use node-fetch or Axios,

example with Axios:

npm i axios

const axios = require('axios');

module.exports.run = async (bot, message, args) => {
  const res = await axios.get('URL HERE')
  message.channel.send(res.data);
}
DedaDev
  • 4,441
  • 2
  • 21
  • 28
  • `console.log(res.data)` right above `message.channel.send` and send response from console here. – DedaDev Oct 02 '19 at 15:19