2017-05-14 184 views
1

我一直在試圖找出將JSON響應插入Google Apps腳本的Google表格中,但由於某些原因,我在嘗試運行時出現錯誤。將JSON響應轉換爲Google表格(Google Apps腳本)

請看截圖和下面的代碼。

function myFunction() { 

    var key_67 = 'YYYYYYYYYYYYYYYYYY'; 
    var ss_67 = SpreadsheetApp.openById(key_67); 
    var sheet_67 = ss_67.getActiveSheet(); 
    sheet_67.getRange('A1:AZ10000').clearContent(); 
var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet'; 
var response = UrlFetchApp.fetch(url); 
var json = response.getContentText(); 
var data = JSON.parse(json); 
Logger.log(data); 



    var stats=[]; //create empty array to hold data points 



    //The following lines push the parsed json into empty stats array 

    stats.push(data.Yearly_Sales); //temp 
    stats.push(data.Email); //dewPoint 
    stats.push(data.Phone); //visibility 

    //append the stats array to the active sheet 
    sheet_67.appendRow(stats) 

} 

enter image description here

+3

當你將Logger.log(json)放入JSON.parse()之前會發生什麼? –

+0

魯本 - 感謝您的回覆..我嘗試了您的建議,但得到相同的錯誤..這是我嘗試使用 'var response = UrlFetchApp.fetch(url); var json = response.getContentText(); Logger.log(json);var data = JSON.parse(json);' –

+0

錯誤:** SyntaxError:意外的標記:v(第11行,文件「ConvertoCSVFromJSON」)** –

回答

0

因此,基於郵差應用你的JSON響應

var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"[email protected]","Phone":"123-032-03323","P‌otentially":50,"Stat‌e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]};

當我使用響應,是:

function JsonResponse(){ 
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"[email protected]","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} ' 
var data = JSON.parse(json); 
Logger.log(data); 
} 

我得到同樣的錯誤像你一樣:

SyntaxError: Unexpected token: v

這使我相信你的API的反應有這個術語var zohoipekuetview65(不確定至於爲什麼?也許是一個bug)

下面的代碼拆分響應字符串給你JSON響應唯一

function trialParse(){ 
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"[email protected]","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} ' 
Logger.log(JsonResponse(json)) 
} 
function JsonResponse(response){ 
    Logger.log(response) 
    var json = response.split("=")[1] 
    var data = JSON.parse(json); 
    Logger.log(data); 
    return data 
} 

使用var data = JsonResponse(json)

最後請注意只需撥打您的代碼上面的功能:由於喬丹提到瑞亞你可以使用Logger.log(json)來輸出你的日誌的響應。要查看您的日誌goto Views> Logs,它會顯示您從Api收到的回覆。