Felix H Felix H - 4 months ago 9
JSON Question

Access Json objects in JavaScript / Twitter API

I'm using the Twitter API as follows:

...
var params = {id: 656958};
client.get('trends/place', params, function(error, tweets, response){
if(error) throw error;
console.log(tweets[0]);
});
...


my Console log looks like this:
Console output
enter image description here
Now i want to store every name with the tweet_volume in a database.
How can I access these key/value pairs?
Thanks for your help!

I tried it like this:

var params = {id: 656958};
client.get('trends/place', params, function(error, tweets, response){
if(error) throw error;
console.log(tweets[0]);
});
var tweets = JSON.parse(tweets[0]);

function getNamePair(){
for (var key in tweets.trends) {
var name = tweets.trends[key].name;
var volume = jsonResponse.trends[key].tweet_volume;
console.log(key, "Name - " + name + ", tweet_vol - " + volume);
}
}
getNamePair();


But I got the error:

var tweets = JSON.parse(tweets[0]);
^

TypeError: Cannot read property '0' of undefined


By using var tweets = JSON.parse(tweets);
I think i access the wrong data.
Output in this case:

undefined:1
undefined
^

SyntaxError: Unexpected token u

Answer

Simply iterate over your json data.

If you are getting response as string, then you may have to parse it to get JavaScript object before iterating it. [See the updated code]. If your response is json(JavaScript object) then you can directly iterate on it.

A simple example :

//if your response is string
var jsonData = "{\"trends\":[{\"name\":\"ABC\",\"tweet_volume\":101},{\"name\":\"XYZ\",\"tweet_volume\":111},{\"name\":\"PQR\",\"tweet_volume\":121}]}";

//parse string to json
var jsonResponse = JSON.parse(jsonData);

function getNamePair() {
  for (var key in jsonResponse.trends) {
    var name = jsonResponse.trends[key].name;
    var volume = jsonResponse.trends[key].tweet_volume;
    console.log(key, "Name - " + name + ", tweet_vol - " + volume);
  }
}

getNamePair();

Store the pairs in a json ,then you can send this data to you server and there save it.

Comments