The following code returns a huge JSON, but I only want to select 4 parameters of all those that are returned to me, what I am doing so far is console.log(tweets);
calling the parameter that I want to select, for example name
, with tweets.name
, but it always tells me that name
it does not it is defined. This would be the code I am using.
The parameters that I want to extract from this JSON are nested in a first instance in user
, and inside user
I have the parameters id
, name
, location
... which are the ones I intend to store.
twitterperfilesCtrl.getPerfiles = async(req, res) =>{
const twitterPerfiles = await twitterPerfil.find();
const contadorPerfiles = await twitterPerfil.countDocuments();
res.json(twitterPerfiles);
//console.log(twitterPerfiles[1].screen_name);
for(i = 0; i < contadorPerfiles; i++){
if (twitterPerfiles[i].id != true) {
var params = {screen_name: twitterPerfiles[i].screen_name};
client.get('statuses/user_timeline', params, function(error, tweets, response) {
if(!error){
console.log(tweets);
}
});
}
}
}
The Twitter documentation: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html
As @JordiHuertas tells you, the problem is in the way you want to access the data. The Twitter API documentation clearly tells you what type of Response you'll get when you make a GET request to the URL with the appropriate parameters.
ISSUE
You want to access the properties of a JSON object returned by the Twitter API.
SOLUTION
According to the Twitter API documentation , the Response returned by making a GET request is a
Array
containing the tweets you're requesting.Each element of
Array
is an object in JSON format, which has the following structure: (Taken from the Twitter documentation, I have modified some attributes for readability)For what you raise in your question, you are interested in extracting or saving the values corresponding to
id
,name
,location
, etc. that are inside the objectuser
of each tweet .The object
user
of each tweet has the following structure: (taken from the Twitter API)Therefore, in order to access the fields you require you can either use a loop
for
to go through theArray
tweets or theforEach()
.Taking the information from what you uploaded to pastebin , this would be a way to get the data:
As you can see, I have used the method
forEach()
, which allows you to iterate through each element of aArray
.For each element of
Array
the function that is passed as a parameter to is executedforEach()
. In this case, the variabletweet
represents an element of theArray
. According to what we saw from the structure of our Response , each element has a valueuser
, and this is why to obtain the desired value we usetweet.user.valor
.I hope this clears your doubt.