google-apps-scriptgoogle-sheetsjsonparser

Google App Script - Json response parsing


I'm using google app script to parse this json response.

enter image description here

Issue

On sheets I get only the values of the first metric not the second one

enter image description here

But I want the values of the second metric as well.

This is what i'm tryng to achieve

enter image description here

Any help?

Thanks


Solution

  • How about this sample script?

    Sample script:

    var json = {locationMetrics:[{metricValues:[{metric:"ACTIONS_DRIVING_DIRECTIONS", dimensionalValues:[{timeDimension:{timeRange:{startTime:"2020-02-01T00:00:00Z"}}, value:3, metricOption:"AGGREGATED_DAILY"}, {value:0, metricOption:"AGGREGATED_DAILY", timeDimension:{timeRange:{startTime:"2020-02-02T00:00:00Z"}}}]}, {metric:"ACTIONS_PHONE", dimensionalValues:[{metricOption:"AGGREGATED_DAILY", timeDimension:{timeRange:{startTime:"2020-02-01T00:00:00Z"}}, value:0}, {timeDimension:{timeRange:{startTime:"2020-02-02T00:00:00Z"}}, value:0, metricOption:"AGGREGATED_DAILY"}]}], timeZone:"Europe/London", locationName:"accounts/xxx/locations/xxx"}]};
    
    // Create an array from "json".
    var locationMetrics = json.locationMetrics;
    var rows = locationMetrics.reduce(function(ar1, obj1) {
      return ar1.concat(obj1.metricValues.reduce(function(ar2, obj2) {
        return ar2.concat(obj2.dimensionalValues.map(function(obj3) {return [obj2.metric, obj3.metricOption, obj3.timeDimension.timeRange.startTime, obj3.value]}));
      }, []));
    }, []);
    
    // Put values to Spreadsheet.
    var sheet = SpreadsheetApp.getActive().getSheetByName('sheet1')
    dataRange = sheet.getRange(2, 1, rows.length, 4); 
    dataRange.setValues(rows);
    

    Result:

    [
        ["ACTIONS_DRIVING_DIRECTIONS","AGGREGATED_DAILY","2020-02-01T00:00:00Z",3],
        ["ACTIONS_DRIVING_DIRECTIONS","AGGREGATED_DAILY","2020-02-02T00:00:00Z",0],
        ["ACTIONS_PHONE","AGGREGATED_DAILY","2020-02-01T00:00:00Z",0],
        ["ACTIONS_PHONE","AGGREGATED_DAILY","2020-02-02T00:00:00Z",0]
    ]
    

    Note:

    References: