Thursday 4 May 2017

Script not reading JSON result - Facebook Graph API

Background - I am trying to export 100 comments from a public Facebook post using Graph API and json2code (a npm package). The issue I am having is trying to get NodeJS to read the file as when running the code I get a blank (empty) result.

var json2csv = require('json2csv');
var fs = require('fs');

// Settings
var accessToken = 'xxx';
var limitCount = 100;
var postID = 'xxxxxxxx';
var fields = ['data.from.name', 'data.message', 'data.like_count', 'data.from.id', 'data.created_time'];

// API
var fbGraph = `https://graph.facebook.com/${postID}/comments?limit=${limitCount}&access_token=${accessToken}`;

console.log(fbGraph);

var csv = json2csv({ data: fbGraph, fields: fields });
console.log(csv);

The console.log(fbGraph); outputs exactly what I need, here is an example of its result when I paste it into my browser:

{
   "data": [
      {
         "created_time": "2017-04-07T00:49:05+0000",
         "from": {
            "name": "xxxxx",
            "id": "xxxxxx"
         },
         "message": "xxxxxxxxxxxx",
         "can_remove": false,
         "like_count": 22,
         "message_tags": [
            {
               "id": "xxxx",
               "length": 7,
               "name": "xxxx",
               "offset": 62,
               "type": "page"
            },
            {
               "id": "xxxx",
               "length": 10,
               "name": "xxxx",
               "offset": 214,
               "type": "page"
            }
         ],
         "user_likes": false,
         "id": "xxx"
      }
   ],
   "paging": {
      "cursors": {
         "before": "xxxx",
         "after": "xxxx"
      },
      "next": "xxxx"
   }
}

Names and personal information were removed to protect privacy

As you already may see I am looking to capture the following (in order) in csv format:

  • data -> from -> name
  • data -> message
  • data -> like_count
  • data -> from -> id
  • data -> created_time

When I run the script, it shows the field names but the data I am trying to grab from Facebook does not appear. If I was to use this script with in-line JSON inside a variable, it works successfully.

Am I doing something wrong? I am fairly new to Javascript so correct me if a process that I am using can be done more efficiently as well.



via Lachie

No comments:

Post a Comment