Mauro Bros
Mauro Bros

Reputation: 91

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

Upvotes: 1

Views: 2195

Answers (1)

Tanaike
Tanaike

Reputation: 201643

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);
  • json is from your question.

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:

  • In this case, the script can work with and without V8.
  • In this sample script, your sample value is used. So it supposes that all keys of "metric", "metricOption", "startTime", "value" are existing. So please be careful about this.

References:

Upvotes: 4

Related Questions