Felix H
Felix H

Reputation: 3

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

Upvotes: 0

Views: 575

Answers (2)

DavidDomain
DavidDomain

Reputation: 15293

You can use

Array.prototype.forEach

The forEach() method executes a provided function once per array element.

arr.forEach(callback[, thisArg])

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

Makes it very simple to target only the properties you are looking for and then do something with them. Here is an example.

// Your tweet data as JSON string.
let tweets = '[{"as_of":"2012-08-24T23:25:43Z","created_at":"2012-08-24T23:24:14Z","locations":[{"name":"Worldwide","woeid":1}],"trends":[{"tweet_volume":3200,"events":null,"name":"#GanaPuntosSi","promoted_content":null,"query":"%23GanaPuntosSi","url":"http://twitter.com/search/?q=%23GanaPuntosSi"},{"tweet_volume":4200,"events":null,"name":"#WordsThatDescribeMe","promoted_content":null,"query":"%23WordsThatDescribeMe","url":"http://twitter.com/search/?q=%23WordsThatDescribeMe"}]}]';

let storeData = ({name, volume}) => console.log(`${name} has a tweet volume of ${volume}`);

JSON.parse(tweets)[0]["trends"].forEach( n => {
  storeData({name: n.name, volume: n.tweet_volume});
});

Upvotes: 0

hityagi
hityagi

Reputation: 5256

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.

Upvotes: 1

Related Questions