2017-01-05 1 views
1

Я пытаюсь заставить следующее работать: JSON отправляется на мой скрипт Google. Теперь я хочу получить конкретные значения из этого сообщения JSON и сохранить их в определенных строках одного конкретного Google Spreadsheet. До сих пор так хорошо, это то, что у меня есть:Использовать данные веб-хоста JIRA в проекте Google Script

function doPost(response) { 

var sheets = SpreadsheetApp.openById('MY SHEET ID'); 

    var dataAll = JSON.parse(response.getContentText()); 

    var nR = getNextRow(sheets) + 1; 

// RECORD DATA IN SPREADSHEET 
sheets.getRangeByName('timestamp').getCell(nR,1).setValue(new Date()); 
sheets.getRangeByName('ticket_id').getCell(nR,1).setValue(dataAll); 

} 

function getNextRow(sheets) { 
    var timestamps = sheets.getRangeByName("timestamp").getValues(); 
    for (i in timestamps) { 
    if(timestamps[i][0] == "") { 
    return Number(i); 
    break; 
}}} 

Он должен хранить ответ и положить его в пустую ячейку «метки времени» диапазона. Но на этот момент ничего не происходит.

Это JSON (Body) из JIRA:

{"timestamp":1483576902984,"webhookEvent":"jira:issue_created","issue_event_type_name":"issue_created","user":{"self":"https://xxx.atlassian.net/rest/api/2/user?username=admin","name":"admin","key":"admin","emailAddress":"[email protected]","avatarUrls":{"48x48":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=48","24x24":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=24","16x16":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=16","32x32":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=32"},"displayName":"Max Mustermann [Administrator]","active":true,"timeZone":"Europe/Berlin"},"issue":{"id":"10057","self":"https://xxx.atlassian.net/rest/api/2/issue/10057","key":"TA-58","fields":{"issuetype":{"self":"https://xxx.atlassian.net/rest/api/2/issuetype/10104","id":"10104","description":"A problem which impairs or prevents the functions of the product.","iconUrl":"https://xxx.atlassian.net/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype","name":"Bug","subtask":false,"avatarId":10303},"timespent":null,"project":{"self":"https://xxx.atlassian.net/rest/api/2/project/10000","id":"10000","key":"TA","name":"Test Area","avatarUrls":{"48x48":"https://xxx.atlassian.net/secure/projectavatar?avatarId=10324","24x24":"https://xxx.atlassian.net/secure/projectavatar?size=small&avatarId=10324","16x16":"https://xxx.atlassian.net/secure/projectavatar?size=xsmall&avatarId=10324","32x32":"https://xxx.atlassian.net/secure/projectavatar?size=medium&avatarId=10324"}},"customfield_10110":null,"fixVersions":[],"customfield_10111":null,"aggregatetimespent":null,"customfield_10112":"Not started","resolution":null,"customfield_10113":null,"customfield_10114":null,"customfield_10104":null,"customfield_10105":null,"customfield_10106":null,"customfield_10107":null,"customfield_10108":null,"customfield_10109":null,"resolutiondate":null,"workratio":-1,"lastViewed":null,"watches":{"self":"https://xxx.atlassian.net/rest/api/2/issue/TA-58/watchers","watchCount":0,"isWatching":false},"created":"2017-01-05T01:41:42.903+0100","priority":{"self":"https://xxx.atlassian.net/rest/api/2/priority/3","iconUrl":"https://xxx.atlassian.net/images/icons/priorities/medium.svg","name":"Medium","id":"3"},"customfield_10100":null,"customfield_10101":null,"customfield_10102":null,"customfield_10103":null,"labels":[],"timeestimate":null,"aggregatetimeoriginalestimate":null,"versions":[],"issuelinks":[],"assignee":null,"updated":"2017-01-05T01:41:42.903+0100","status":{"self":"https://xxx.atlassian.net/rest/api/2/status/10000","description":"","iconUrl":"https://xxx.atlassian.net/","name":"To Do","id":"10000","statusCategory":{"self":"https://xxx.atlassian.net/rest/api/2/statuscategory/2","id":2,"key":"new","colorName":"blue-gray","name":"To Do"}},"components":[],"timeoriginalestimate":null,"description":"super alles neu","timetracking":{},"customfield_10005":null,"attachment":[],"aggregatetimeestimate":null,"summary":"super alles neu","creator":{"self":"https://xxx.atlassian.net/rest/api/2/user?username=admin","name":"admin","key":"admin","emailAddress":"[email protected]","avatarUrls":{"48x48":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=48","24x24":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=24","16x16":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=16","32x32":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=32"},"displayName":"Max Mustermann [Administrator]","active":true,"timeZone":"Europe/Berlin"},"subtasks":[],"reporter":{"self":"https://xxx.atlassian.net/rest/api/2/user?username=admin","name":"admin","key":"admin","emailAddress":"[email protected]","avatarUrls":{"48x48":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=48","24x24":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=24","16x16":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=16","32x32":"https://secure.gravatar.com/avatar/3d238d8be45bd26982fa09ae2f891c3f?d=mm&s=32"},"displayName":"Max Mustermann [Administrator]","active":true,"timeZone":"Europe/Berlin"},"customfield_10000":"{}","aggregateprogress":{"progress":0,"total":0},"customfield_10001":null,"customfield_10115":null,"customfield_10116":"0|i0005r:","environment":null,"duedate":null,"progress":{"progress":0,"total":0},"comment":{"comments":[],"maxResults":0,"total":0,"startAt":0},"votes":{"self":"https://xxx.atlassian.net/rest/api/2/issue/TA-58/votes","votes":0,"hasVoted":false},"worklog":{"startAt":0,"maxResults":20,"total":0,"worklogs":[]}}}} 

Однако, я не хочу, чтобы весь JSON в моей камере, я только хочу, чтобы иметь конкретные obejcts/идентификатор изнутри JSON. Как мне их назвать?

+0

Этот пост нуждается в большом количестве исправлений; происходит слишком много жаргонов, и никто не заботится о том, откуда приходит JSON, и о том, какие свойства вас интересуют без обид. Давайте начнем с указания, какая переменная хранит JSON ... – Rafael

+0

'getCell()' должен предоставить вам ячейку по вашему выбору, 'setValue()' будет устанавливать соответствующую ячейку для любых данных, которые вы хотите; Вот и все. – Rafael

+0

Спасибо @ Rafael - getCell и setValue - это то, что у меня уже есть, и оно работает, но как я могу получить один конкретный объект из JSON и установить его как значение для ячейки? ... JSON хранится в req, правильно? Я также попробовал 'var dataAll = JSON.parse (req.getContentText()); var data = dataAll.timestamp; sheets.getRangeByName ('ticket_id'). GetCell (nR, 1) .setValue (данные); } ' –

ответ

1

После тонн исследований, это решение, которое работает для меня (в моем случае):

function doPost(response) { 

    var sheets = SpreadsheetApp.openById('SHEET_ID'); 

// retrieve data from JIRA Payload and store them into "data" 

    var json = response.postData.contents; 
    var data = JSON.parse(json); 

// index values from "data" and store them into seperate variables 
// for example: 
    var ticket_id = data.issue.key; 
    var priority_name = data.issue.fields.priority.name; 
    var summary = data.issue.fields.summary; 

Эти две линии:

var json = response.postData.contents; 
var data = JSON.parse(json); 

Сделано это можно прочитать body и указательный все специфические параметры, которые я хочу.

1

Вот пример:

/* 
* webhookHandler: JIRA webhook callback function 
*/ 
function webhookHandler(response) { 
    var data = response.getAs("application/json"); 
    //logs out data in dev console 
    console.log(data); 

    var spreadsheet = SpreadsheetApp.openById("<spreadsheet id>"); 
    var cellRange = spreadsheet.getRangeByName("<some range name>"); 
    var cell = cellRange.getCell(0 /*row index*/, 0/*column index*/); 

    cell.setValue(data.ticket_id/*index the JSON object returned by response*/); 
} 

UrlFetchApp Documentation

SpreadsheetApp Documentation

+0

Это потрясающе! Но в моем случае у меня нет '' ", я использую веб-хосты JIRA для автоматической отправки JSON, когда я делаю вещи в JIRA, в скрипт Google. Как ваш код будет работать с этим? Я очень ценю ваши мысли :) –

+0

обновил мой ответ – Rafael

+0

Спасибо @ Rafael! Это сработало для меня «var json = response.postData.contents; var data = JSON.parse (json); ' –

Смежные вопросы