App script once a week asking for authorization - google-apps-script

I did a script (I'm not a programer) and I'm running to get a csv from metabase question. The only problem is because once a week as asking me to authorize again.
It shows:
"Authorisation required" "A script attached to this document needs your permission to run."
image step 02
image step 03
image step 04
What can I do to authorize forever?
I need to have the authorization forever. Not needed to authorize once a week because I'm running on time-base and automated. The code is below.
I have two files Code.gs and Code2.gs - on the first one I have another code.
function onInstall() {
onOpen();
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Import Question & Send Email')
.addItem('Import Question', 'importQuestion')
.addItem('Send Report by e-mail', 'sendReport')
.addToUi();
}
function importQuestion() {
var status = getQuestionAsCSV(metabaseQuestionNum, true);
var scriptProp = PropertiesService.getScriptProperties();
var metabaseQuestionNum = scriptProp.getProperty('QUESTION_ID');
var log = {
'user': Session.getActiveUser().getEmail(),
'function': 'importQuestion',
'questionNumber': metabaseQuestionNum,
'status': status
};
if (log.status === true) {
console.log(log);
} else {
console.error(log);
}
}
function getSheetNumbers() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var questionNumbers = [];
for (var i in sheets) {
var sheetName = sheets[i].getName();
if (sheetName.indexOf('(metabase/') > -1) {
var questionMatch = sheetName.match('\(metabase\/[0-9]+\)');
if (questionMatch !== null) {
var questionNumber = questionMatch[0].match('[0-9]+')[0];
if (!isNaN(questionNumber) && questionNumber !== '') {
questionNumbers.push({
'questionNumber': questionNumber,
'sheetName': sheetName
});
}
}
}
}
return questionNumbers;
}
function getToken(baseUrl, username, password) {
var sessionUrl = baseUrl + "api/session";
var options = {
"method": "post",
"headers": {
"Content-Type": "application/json"
},
"payload": JSON.stringify({
username: username,
password: password
})
};
var response;
try {
response = UrlFetchApp.fetch(sessionUrl, options);
} catch (e) {
throw (e);
}
var token = JSON.parse(response).id;
return token;
}
function getQuestionAndFillSheet(baseUrl, token, metabaseQuestionNum, sheetName) {
var questionUrl = baseUrl + "api/card/" + metabaseQuestionNum + "/query/csv";
var options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
"X-Metabase-Session": token
},
"muteHttpExceptions": true
};
var response;
try {
response = UrlFetchApp.fetch(questionUrl, options);
} catch (e) {
return {
'success': false,
'error': e
};
}
var statusCode = response.getResponseCode();
if (statusCode == 200 || statusCode == 202) {
var values = Utilities.parseCsv(response.getContentText());
try {
fillSheet(values, sheetName);
return {
'success': true
};
} catch (e) {
return {
'success': false,
'error': e
};
}
} else if (statusCode == 401) {
var scriptProp = PropertiesService.getScriptProperties();
var username = scriptProp.getProperty('USERNAME');
var password = scriptProp.getProperty('PASSWORD');
var token = getToken(baseUrl, username, password);
scriptProp.setProperty('TOKEN', token);
var e = "Error: Could not retrieve question. Metabase says: '" + response.getContentText() + "'. Please try again in a few minutes.";
return {
'success': false,
'error': e
};
} else {
var e = "Error: Could not retrieve question. Metabase says: '" + response.getContentText() + "'. Please try again later.";
return {
'success': false,
'error': e
};
}
}
function fillSheet(values, sheetName) {
var colLetters = ["N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ"];
var sheet;
if (sheetName == false) {
sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
} else {
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('AUTO-productivity');
}
var range = sheet.getRange(1,14,1000,4);
range.clear({contentsOnly: true});
var rows = values;
var header = rows[0];
var minCol = colLetters[0];
var maxCol = colLetters[header.length - 1];
var minRow = 1;
var maxRow = rows.length;
var range = sheet.getRange(minCol + minRow + ":" + maxCol + maxRow);
range.setValues(rows);
}
function getQuestionAsCSV(metabaseQuestionNum, sheetName) {
var scriptProp = PropertiesService.getScriptProperties();
var baseUrl = scriptProp.getProperty('BASE_URL');
var username = scriptProp.getProperty('USERNAME');
var password = scriptProp.getProperty('PASSWORD');
var token = scriptProp.getProperty('TOKEN');
var metabaseQuestionNum = scriptProp.getProperty('QUESTION_ID');
if (!token) {
token = getToken(baseUrl, username, password);
scriptProp.setProperty('TOKEN', token);
}
status = getQuestionAndFillSheet(baseUrl, token, metabaseQuestionNum, sheetName);
return status;
}

Maybe you could try to add scopes in manifest file
In project file, open Setup, and check display manifest file "appsscript.json", and then open it.
Add:
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/script.send_mail",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/gmail.modify",
]
Reference :
Scopes
List of scopes

Related

JSON to cell google sheet array work but object not working by binanace API

this is Response:
{
"makerCommission": 15,
"takerCommission": 15,
"buyerCommission": 0,
"sellerCommission": 0,
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"updateTime": 123456789,
"accountType": "SPOT",
"balances": [
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "4763368.68006011",
"locked": "0.00000000"
}
],
"permissions": [
"SPOT"
]
}
This is my code :
var jsonResponce = JSON.parse(data); // To JSON
Logger.log(jsonResponce.accountType); // Return SPOT
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rows = [],
balanc;
for (i = 0; i < jsonResponce.length; i++) {
balanc = jsonResponce[i];
rows.push([balanc.accountType]);
}
Logger.log(rows); /////////////// return [] why not return SPOT
dataRange = sheet.getRange(1, 1, rows.length, 1);
dataRange.setValues(rows);
The JSON return accountType if run without array but after add in array give me [] empty any help pls.
this is picture:
enter image description here
function myfunk() {
const data = '{"makerCommission":15,"takerCommission":15,"buyerCommission":0,"sellerCommission":0,"canTrade":true,"canWithdraw":true,"canDeposit":true,"updateTime":123456789,"accountType":"SPOT","balances":[{"asset":"BTC","free":"4723846.89208129","locked":"0.00000000"},{"asset":"LTC","free":"4763368.68006011","locked":"0.00000000"}],"permissions":["SPOT"]}';
const obj = JSON.parse(data);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const vs = obj.balances;
const oA = vs.map(obj => [obj.asset,obj.free,obj.locked]);
sh.getRange(1,1,oA.length, oA[0].length).setValues(oA);
}
Sheet1:
Col1
Col2
Col3
BTC
4723846.892
0
LTC
4763368.68
0
The reason why your rows is empty is because your jsonResponce is not an array. If you will log jsonResponce.length it will return null.
Sample code:
function myFunction() {
var jsonData = [{
"makerCommission": 15,
"takerCommission": 15,
"buyerCommission": 0,
"sellerCommission": 0,
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"updateTime": 123456789,
"accountType": "SPOT",
"balances": [
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "4763368.68006011",
"locked": "0.00000000"
}
],
"permissions": [
"SPOT"
]
}];
var data = JSON.stringify(jsonData);
var jsonResponce = JSON.parse(data); // To JSON
Logger.log(jsonResponce);
Logger.log(Array.isArray(jsonResponce))
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
Logger.log(jsonResponce.length);
var rows = [],
balanc;
for (i = 0; i < jsonResponce.length; i++) {
balanc = jsonResponce[i];
rows.push([balanc.accountType]);
}
Logger.log(rows); /////////////// return [] why not return SPOT
dataRange = sheet.getRange(1, 1, rows.length, 1);
dataRange.setValues(rows);
}
Modifications done:
create a json array. (encapsulate original json data with [])
Output:
6:37:31 AM Notice Execution started
6:37:31 AM Info [{canDeposit=true, sellerCommission=0.0, balances=[{locked=0.00000000, asset=BTC, free=4723846.89208129}, {locked=0.00000000, asset=LTC, free=4763368.68006011}], takerCommission=15.0, permissions=[SPOT], canTrade=true, makerCommission=15.0, updateTime=1.23456789E8, buyerCommission=0.0, accountType=SPOT, canWithdraw=true}]
6:37:32 AM Info 1.0
6:37:32 AM Info [[SPOT]]
6:37:34 AM Notice Execution completed
Note:
You can use Array.isArray(), to check if the variable is an array or not then read the data accordingly.
Sample:
if(Array.isArray(jsonResponce)){
for (i = 0; i < jsonResponce.length; i++) {
balanc = jsonResponce[i];
rows.push([balanc.accountType]);
}
}else{
rows.push([jsonResponce.accountType])
}
(UPDATE)
If you want to make the Binance API response into an array, you can append "[" and "]" on your data.
Sample:
var jsonData = {
"makerCommission": 15,
"takerCommission": 15,
"buyerCommission": 0,
"sellerCommission": 0,
"canTrade": true,
"canWithdraw": true,
"canDeposit": true,
"updateTime": 123456789,
"accountType": "SPOT",
"balances": [
{
"asset": "BTC",
"free": "4723846.89208129",
"locked": "0.00000000"
},
{
"asset": "LTC",
"free": "4763368.68006011",
"locked": "0.00000000"
}
],
"permissions": [
"SPOT"
]
};
var data = JSON.stringify(jsonData);
data = "["+data+"]";
var jsonResponce = JSON.parse(data); // To JSON
Logger.log(jsonResponce);
Logger.log(Array.isArray(jsonResponce))
Output:
12:21:48 AM Info [{makerCommission=15.0, canDeposit=true, balances=[{free=4723846.89208129, locked=0.00000000, asset=BTC}, {free=4763368.68006011, asset=LTC, locked=0.00000000}], takerCommission=15.0, updateTime=1.23456789E8, accountType=SPOT, canTrade=true, sellerCommission=0.0, buyerCommission=0.0, canWithdraw=true, permissions=[SPOT]}]
12:21:48 AM Info true

discord/google forms webhook only works when im the one posting, how can i fix this

the webhook only runs when im the one posting to it, the permissions are set to anyone but that has not helped, it worked just fine not 2 months ago then google and discord changed some things and now its broken.
var POST_URL = "https://discord.com/api/webhooks/sI9VjZ_v0TsMNA5yBWmkopvFX";
function onSubmit(e) {
var form = FormApp.getActiveForm();
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var response = latestResponse.getItemResponses();
var items = [];
for (var i = 0; i < response.length; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
try {
var parts = answer.match(/[\s\S]{1,1024}/g) || [];
} catch (e) {
var parts = answer;
}
if (answer == "") {
continue;
}
for (var j = 0; j < parts.length; j++) {
if (j == 0) {
items.push({
"name": question,
"value": parts[j],
"inline": false
});
} else {
items.push({
"name": question.concat(" (cont.)"),
"value": parts[j],
"inline": false
});
}
}
}
var options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
},
"payload": JSON.stringify({
"content": "‌", // This is not an empty string
"embeds": [{
"title": "Pirate Hunting",
"fields": items,
"footer": {
"text": "Happy Hunting"
}
}]
})
};
UrlFetchApp.fetch(POST_URL, options);
};
is there something wrong with the code or is this a permissions problem

Google form notification script

The notification script give title and value, and I am trying to get value only without title
Google Form script
Method1
var POST_URL = "hidden url";
function onSubmit(e) {
var response = e.response.getItemResponses();
var items = [];
for (var i = 0; i < response.length ; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
var parts = answer.match(/[\s\S]{1,1024}/g) || [];
if (answer == "") {continue;}
for (var j = 0; j< parts.length; j++) {
if (j == 0) {
items.push({"name": question, "value": parts[j], "inline": true});
} else {
items.push({"name": question.concat(" (cont.)"), "value": parts[j], "inline": true});
}
}
}
var options = {
"method" : "post",
"payload": JSON.stringify({
"embeds": [
{
"title":"New request",
"fields":items,
}
]
}
)
};
UrlFetchApp.fetch(POST_URL, options);
};
Method2 added
function onFormSubmit(e) {
var fields = [];
for (i = 0; i < e.response.getItemResponses().length; i++) {
var response = e.response.getItemResponses()[i];
fields.push({
"name": response.getItem().getTitle(),
"value": JSON.stringify(response.getResponse()),
"inline": false
});
}
var data = {
"embeds": [{
"title": "**Test Rep** — " + (e.source.getTitle() != null && e.source.getTitle().length > 0 ? e.source.getTitle() : "Untitled Form"),
"type": "rich",
"fields": fields,
}]
};
var options = {
method: "post",
payload: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
muteHttpExceptions: true,
};
Logger.log("Attempting to send:");
Logger.log(JSON.stringify(data));
var response = UrlFetchApp.fetch("Hidden URL", options);
Logger.log(response.getContentText());
};
The method2 do same job as method1 but i hope someone can help to workaround
I expected to get notification with form title + the value of two fields without question title.
The problem
A form has the title "New request" and has two questions.
The notification should have the form title "New request" and the answers to the questions but not the questions themselves.
A solution
Try these steps:
(1) Remove or comment out
var question = response[i].getItem().getTitle();
(2) Change this
items.push({"name": question, "value": parts[j], "inline": true});
to
items.push({"value": parts[j], "inline": true});
(3) Change this
items.push({"name": question.concat(" (cont.)"), "value": parts[j], "inline": true});
to
items.push({"value": parts[j], "inline": true});

Google App script - Telegram Bot - Inline Keyboard callback_query

This here is my function that hears for anything incoming from Telegram. It does work well with any message and files or whatever but it doesn't work when i press a but of an inline_keyboard, Why?
How can i create a function that hears for a inline_keyboard button pressed?
function doPost(e) {
var data = JSON.parse(e.postData.contents);
sendText('personal_chat_id', JSON.stringify(data));
}
In case you need it here under is my function that can send a message with an inline_keyboard.
function lol(){
var keyboard ={
inline_keyboard: [
[
{
text: "A",
callback_data: 123
},
{
text: "B",
callback_data: 234
}
],
[
{
text: "C",
callback_data: 345
},
{
text: "D",
callback_data: 456
}
]
]
}
sendText('personal_chat_id', "lol", keyboard)
}
function sendText(chatId,text,keyBoard){
keyBoard = keyBoard || 0;
if(keyBoard.inline_keyboard || keyBoard.keyboard){
var data = {
method: "post",
payload: {
method: "sendMessage",
chat_id: String(chatId),
text: text,
parse_mode: "HTML",
reply_markup: JSON.stringify(keyBoard)
}
}
}
var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
return response.getContentText()
}
You need to do it inside the doPost(e) function. Take the "e" parameter and verify what kind of type it is. If it is "contents.callback_query" is coming from the inline keyboard response and if it is "contents.message" it's text typed by the user.
And dont forget declare sendText() and sendKeyboard() functions.
function doPost(e) {
var contents = JSON.parse(e.postData.contents);
var keyboard = {
"inline_keyboard": [
[{
"text": "Players",
"callback_data": "player"
}],
[{
"text": "Match",
"callback_data": "match"
}],
[{
"text": "Results",
"callback_data": "result"
}]
]}
if (contents.callback_query) {
var id = contents.callback_query.message.chat.id;
var text = contents.callback_query.data;
switch (text) {
case 'Player':
var answer = 'Ingresa tu nombre y apellido';
sendText(id, answer);
break;
case 'match':
var answer = 'Ingresá tu nombre y apellido';
sendText(id, answer);
break;
case 'result':
var keyboard = {
'inline_keyboard': [
[{
'text': 'Youtube',
'url': 'https://youtube.com'
},{
'text': 'Google',
'url': 'https://google.com'
}]
]
};
sendTextWithButtons(id, 'Algunos enlaces', JSON.stringify(keyboard));
break;
default:
var answer = 'Default answer';
sendText(id, answer);
break;
}
var chat_id = contents.callback_query.from.id;
var user = contents.callback_query.message.chat.first_name;
var cb_data = contents.callback_query.data;
sendText(chat_id, CariDataDariIDSheet(cb_data));
}else if (contents.message) {
var chat_id = contents.message.from.id;
var user = contents.message.chat.first_name;
var answer = "your answer";
sendKeyboard(chat_id, answer, keyboard);
}
}

Merge the two different JSON using node JS

I have two requests that return their data as JSON using NodeJS Seriate.
The first response is:
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]
}
The second response is:
{
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
}
I want to merge the two responses, that would have the following structure:
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014",
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
}
}
}
]
}
I searched and found several methods of joining or extending two JSON objects but nothing similar to that.
How can I achieve this?
My Actual Code is,
exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
status : Boolean,
message : String,
data : String
};
var request = require('request');
var username = const.username ;
var password = const.password ;
var options = {
url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
auth : {
username : username,
password : password
}
};
request( options, function(error, obj) {
if (error) {
response.message = appmsg.DATA_NT_FOUND;
response.status = false;
response.data = obj;
res.send(response);
} else {
response.message = appmsg.DATA_FOUND;
response.status = true;
response.data = JSON.parse(obj.body);
//res.send(response);
var issueKey = response.data.issues;
// var keyData = issueKey[0].key;
// console.log(response.data.issues);
// console.log(keyData);
var output = [];
for(var i = 0; i < issueKey.length; i++) {
var issue = issueKey[i].key;
//var key = [];
//key.push(issue);
console.log(issue);
var respon = {
status : Boolean,
message : String,
data : String
};
var request = require('request'),
username = const.username ,
password = const.username ,
url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
request({url : url,headers : {"Authorization" : auth}}, function(err, object){
if (object) {
var info = object;
output.push(info); // this is not working as ouput is undefined at this point
//var pout = JSON.parse(output);
//console.log(info);
console.log("==============================================================================");
//console.log(output);
console.log("******************************************************************************");
if(issueKey.length === output.length){
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = output;
//console.log(output);
//res.send(respon);
var id = issueKey[0].id;
console.log(id);
var commitout = [];
for(var i = 0; i < issueKey.length; i++) {
var commits = issueKey[i].id;
console.log(commits);
var request = require('request'),
username = const.username ,
password = const.password ,
url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
//console.log(url);
var test = [];
request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
if (obj1) {
var info1 = obj1.body;
commitout.push(info1);
if(issueKey.length === commitout.length){
respon.message = appmsg.DATA_FOUND;
respon.status = true;
respon.data = commitout;
// console.log(commitout);
//var test = merge(output, commitout);
var text = output.body;
var resultdone = output;
resultdone.data = resultdone + commitout.body;
console.log(resultdone.data);
res.send(resultdone.data);
}
}
});
}
}
}
});
}
}
});
};
How can i merge the two arrays? in one response. That is my question..
Never mainpulate the string of JSON directly. Parse it first.
const firstRes = JSON.parse(firstResJson);
const secondRes = JSON.prase(secondResJson);
Now, it's a bit unclear what you want to do, and why you want to do it, but try this:
firstRes.data.body.fields.parent.detail = secondRes.body.detail;
Then, you'll find your combined data in firstRes. To get it back to JSON:
JSON.stringify(firstRes);
var obj1 = {
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]};
var obj2 = {
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]}
}
obj1.data.forEach(function(item, index){
item.body.fields.parent.detail = r.body.detail[index];
});
console.log(obj1);
var result1 =
{
"status": true,
"message": "Data Found",
"data": [
{
"statusCode": 200,
"body": {
"expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
"id": "64672",
"self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
"key": "CKS-2016",
"fields": {
"parent": {
"id": "64670",
"key": "CKS-2014"
}
}
}
}
]
}
var text = result1.data[0].body;
var result2 =
{
"statusCode": 200,
"body": {
"errors": [],
"detail": [
{
"repositories": [
{
"name": "registry",
"avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
"avatarDescription": "services"
}
]
}
]
}
};
var resultdone = result1;
resultdone.data[0].body.fields.parent= result2.body.detail;