2017-12-03 191 views
0

我正在使用google trends API最終將趨勢數據導出到excel文件。問題是我只想提取關鍵字的格式化時間和值。如何抓取JavaScript中的鍵值對 - Google Trends API

JS不是我的強項。我如何只拉這些參數?或者有沒有辦法將這些參數分配給鍵值字典對?

謝謝。

JSON輸出

{ 
    "default": { 
    "timelineData":[ 
     { 
     "time":"1511629200", 
     "formattedTime":"Nov 25, 2017 at 12:00 PM", 
     "formattedAxisTime":"Nov 25 at 12:00 PM", 
     "value":[44], 
     "formattedValue":["44"] 
     }, 
     { 
     "time":"1511632800", 
     "formattedTime":"Nov 25, 2017 at 1:00 PM", 
     "formattedAxisTime":"Nov 25 at 1:00 PM", 
     "value":[41], 
     "formattedValue":["41"] 
     } 
    ] 
    } 
} 

代碼

'use strict'; 

const googleTrends = require('google-trends-api'); 


var animals = ['hamsters', 'puppies']; 


for (var key in animals) { 

    console.log(animals[key]); 

    googleTrends.interestOverTime({ 
     keyword: key, 
     startTime: new Date(Date.now() - (167.9 * 60 * 60 * 1000)), 
     granularTimeResolution: true, 
    }, function(err, results) { 

     if (err) 
      console.log('oh no error!', err); 
     else 
      console.log(results); 
     console.log("--------------------------") 
    }); 
} 
+0

你的JSON對象還具有一個錯誤的額外'}' – Alan

回答

0

這可能讓您開始提取你想要什麼:

theStuffIWant = []; 

for (each of output.default.timelineData) { 
    theStuffIWant.push({time: each.formattedTime, value: each.value[0]}); 
} 

console.log(theStuffIWant); 

// now you should have an array of the data you want. 

注意,值看起來像他們在具有一個值的數組,因此需要使用[0]索引。還要注意,變量output應該替換爲任何包含您的JSON數據的變量。

+0

獲取「類型錯誤:無法讀取未定義的屬性「默認」。 – Phum

1

提取所需的數據轉換成一個目的是遵循以功能性方式一鍵/值對圖案與存在檢查:

function extractTimeAndValue(data) { 
    var timelineData = (data && data.default && data.default.timelineData) || []; 

    return timelineData.reduce(function(timeAndValueObject, timeline) { 
    var time = timeline.formattedTime; 
    var value = timeline.value; 

    return Object.assign(
    {}, 
    timeAndValueObject, 
    time && value ? {[time]: value} : {} 
    ); 
    }, {}); 
} 
相關問題