如何解析Facebook Graph API“小时”响应

时间:2014-07-26 21:50:11

标签: javascript facebook facebook-graph-api

我正在使用Facebook Graph API从Facebook页面获取一些数据,但我不知道如何在"小时"这是这样的:

  {
    "wed_1_open": "17:00", 
    "wed_1_close": "02:00", 
    "thu_1_open": "17:00", 
    "thu_1_close": "02:00", 
    "fri_1_open": "17:00", 
    "fri_1_close": "02:00", 
    "sat_1_open": "12:00", 
    "sat_1_close": "02:00", 
    "sun_1_open": "12:00", 
    "sun_1_close": "20:00"
  }

所以我想知道如何解析这个结果,以获得一些人类可读的文本,如信息标签中的文字:

wed - fri: 17:00 - 2:00
sat: 12:00 - 2:00
sun: 12:00 - 20:00

提前感谢!!

1 个答案:

答案 0 :(得分:6)

以下是一种方法:http://jsbin.com/xavaxudi/1/edit?js,console

注意:这是我刚刚在几分钟内写完的内容。如果您正在处理大量数据,那么您可能需要相应地进行优化。

var rawFbData = {
    "wed_1_open": "17:00", 
    "wed_1_close": "02:00", 
    "thu_1_open": "17:00", 
    "thu_1_close": "02:00", 
    "fri_1_open": "17:00", 
    "fri_1_close": "02:00", 
    "sat_1_open": "12:00", 
    "sat_1_close": "02:00", 
    "sun_1_open": "12:00", 
    "sun_1_close": "20:00"
  };

console.log(rawFbData);

var formattedData = {};
for (var key in rawFbData) {
  if (key.substr(-5) === '_open') {
    var openDay = key.substr(0, 3);
    var openTime = rawFbData[key];

    var endTimeKey = key.replace('_open', '_close');
    var endTime = rawFbData[endTimeKey];

    var formattedDataKey = openTime + ' - ' + endTime;

    if (formattedData[formattedDataKey] === undefined) {
     formattedData[formattedDataKey] = []; 
    }

    formattedData[formattedDataKey].push(openDay);
  }  
}

//console.log(formattedData);

for (var formattedDatakey in formattedData) {
  var formattedDatakeyLen = formattedData[formattedDatakey].length;

  if (formattedDatakeyLen > 1) {
    var firstDay = formattedData[formattedDatakey][0];
    var lastDay = formattedData[formattedDatakey][formattedDatakeyLen - 1];

    console.log(firstDay + ' - ' + lastDay + ': ' + formattedDatakey);
  }
  else if (formattedData[formattedDatakey].length === 1) {
    console.log(formattedData[formattedDatakey][0] + ': ' + formattedDatakey);
  }
}