I am currently facing a perplexing issue while working with the Twitter API.
Below is the script causing the confusion:
const Twitter = require('twitter-api-stream')
const twitterCredentials = require('./credentials').twitter
const twitterApi = new Twitter(twitterCredentials.consumerKey, twitterCredentials.consumerSecret, function(){
console.log(arguments)
})
twitterApi.getUsersTweets('everycolorbot', 1, twitterCredentials.accessToken, twitterCredentials.accessTokenSecret, (error, result) => {
if (error) {
console.error(error)
}
if (result) {
console.log(result) // outputs an array of json objects
console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
console.log(result[0]) // outputs a opening bracket ('[')
console.log(result[0].text) // outputs undefined
}
})
This script calls the following function to interact with Twitter:
TwitterApi.prototype.getUsersTweets = function (screenName, statusCount, userAccessToken, userRefreshToken,cb ) {
var count = statusCount || 10;
var screenName = screenName || "";
_oauth.get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?count=" + count + "&screen_name=" + screenName
, userAccessToken
, userRefreshToken
, cb
);
};
The output seems positive when logging the result itself:
[
{
"created_at": "Thu Sep 01 13:31:23 +0000 2016",
"id": 771339671632838656,
"id_str": "771339671632838656",
"text": "0xe07732",
"truncated": false,
...
}
]
However, I encounter issues accessing this array:
console.log(result.length) //outputs 3506 for some reason (it's only an array of 1)
console.log(result[0]) // outputs a opening bracket ('[')
console.log(result[0].text) // outputs undefined
I revisited the API documentation for the user_timeline, but did not find any special output mentioned.
Any suggestions?
Update
Thanks @nicematt for pointing out the solution.
To clarify the fix, I updated my code as follows and now getting the desired result:
if (result) {
let tweet = JSON.parse(result)[0] // parses the json and returns the first index
console.log(tweet.text) // outputs '0xe07732'
}
Thank you for your assistance!