简体   繁体   中英

How can i get data from a JSON array in google app script?

I'm doing a request to an API that is successful but i need to get the data of the array returned, below i will put how the array looks like so you can help me to extract the data

{ total_grand: 30600000,
  total_billable: null,
  total_currencies: [ { currency: null, amount: null } ],
  total_count: 5,
  per_page: 50,
  data: 
   [ { id: 13998122,
       pid: 1570982183,
       tid: null,
       uid: 5386231,
       description: 'Finish the first part of the RCP mockup',
       start: '2020-03-26T13:00:00-04:00',
       end: '2020-03-26T16:00:00-04:00',
       updated: '2020-04-02T13:25:15-04:00',
       dur: 10800000,
       user: 'Jose',
       use_stop: true,
       client: 'PLA',
       project: 'Training',
       project_color: '0',
       project_hex_color: '#3750b5',
       task: null,
       billable: null,
       is_billable: false,
       cur: null,
       tags: [] 
   } ]
}

I want to access to the user,project,tags,client,start,end and description so i can put it in my SpreadSheet. How can i do that?

This is how i do the request and how i try to access to the data in the array in my variable togglData

for (var i = 0; i < projects.length; i++) {
    var listProjects = projects[i];
    var reportURL = baseURL + '/reports/api/v2/details' + params;
    var reportFetch = UrlFetchApp.fetch(reportURL, options);
    var togglReport = JSON.parse(reportFetch.getContentText());
    var togglData = togglReport["data"]["user"];
    Logger.log(togglReport);
  }

Range.setValues() is used to the set data as a two dimensional array to the sheet. Using destructuring assignment and for...of loop , It's possible to mould the data to a 2D array.

 const togglReport = { total_grand: 30600000, total_billable: null, total_currencies: [{ currency: null, amount: null }], total_count: 5, per_page: 50, data: [ { id: 13998122, pid: 1570982183, tid: null, uid: 5386231, description: 'Finish the first part of the RCP mockup', start: '2020-03-26T13:00:00-04:00', end: '2020-03-26T16:00:00-04:00', updated: '2020-04-02T13:25:15-04:00', dur: 10800000, user: 'Jose', use_stop: true, client: 'PLA', project: 'Training', project_color: '0', project_hex_color: '#3750b5', task: null, billable: null, is_billable: false, cur: null, tags: [], }, ], }; const out = []; for (const { user, project, tags, client, start, end, description, } of togglReport.data) { //We're looping over togglReport.data and not togglReport out.push([user, project, tags.join(), client, start, end, description]); } console.log(out); //SpreadsheetApp.getActive().getSheets[0].getRange(1,1, out.length, out[0].length).setValues(out);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM