Decode a GA4 report using its response headers, not an array position remembered from an earlier request. A new metric or changed ordering can leave every value syntactically valid while assigning counts to a duration column. That is a consumer defect, not evidence that the content's performance changed.
The practical deliverable is a small header-indexed decoder with known input and output. Use synthetic response-shaped records to test it locally, then have the authorized owner verify the actual supported report fields and source response. No customer data or API request is required for the local fixture.
Follow The Response's Own Column Contract
Google's RunReportResponse reference states that dimension-header and metric-header counts and ordering match the respective values in rows. MetricHeader supplies the name and data type, and the row's MetricValue definition represents the metric value as a string.
The metric-type reference distinguishes integer, floating-point and specialized units such as seconds. Parse according to the returned contract and retain the unit. A duration string of 1.5 seconds is 1500 milliseconds, not 1.5 milliseconds.
This differs from the nested-parameter guide. That procedure protects event grain when unnesting exported arrays. Here the source is an aggregated report with header/value alignment.
Freeze Two Reordered Synthetic Responses
For teaching, use eventCount and averageSessionDuration as recognizable names in response-shaped data. The fixtures are invented, not captured Google responses, and do not certify that a particular dimension/metric combination is supported in a real property. Confirm actual request compatibility separately.
| Fixture | Header sequence | Row metric-value strings | Intended interpretation |
|---|---|---|---|
| A | eventCount INTEGER; averageSessionDuration SECONDS | 12;1.5 | 12 events;1.5 seconds |
| B | averageSessionDuration SECONDS; eventCount INTEGER | 1.5;12 | Same 12 events and 1.5 seconds |
| C | Same headers as A | 0;0 | Observed zero values in fixture, not missing fields |
| D | Same headers as A | 12 only | Reject malformed row shape |
A positional parser that always reads the first value as eventCount will break B. A parser that fills D's missing duration with zero will fabricate an observation. The expected output needs metric identities as well as numeric values.
Execute A Bounded Decoder
This Python handles only the three explicitly supported metric types. Unknown types fail rather than silently becoming generic floats. It makes no request and intentionally does not implement every API response field.
import math
from copy import deepcopy
a = {"metricHeaders": [
{"name": "eventCount", "type": "TYPE_INTEGER"},
{"name": "averageSessionDuration", "type": "TYPE_SECONDS"}],
"rows": [{"metricValues": [{"value": "12"}, {"value": "1.5"}]}]}
def decode(report):
headers = report["metricHeaders"]
assert len({h["name"] for h in headers}) == len(headers)
assert {h["name"] for h in headers} == {"eventCount", "averageSessionDuration"}
output = []
for row in report["rows"]:
values = row["metricValues"]
assert len(values) == len(headers)
decoded = {}
for header, cell in zip(headers, values):
raw, kind = cell["value"], header["type"]
assert isinstance(raw, str)
if kind == "TYPE_INTEGER":
value = int(raw)
elif kind in {"TYPE_FLOAT", "TYPE_SECONDS"}:
value = float(raw)
assert math.isfinite(value)
else:
raise ValueError("Unsupported metric type")
decoded[header["name"]] = {"value": value, "type": kind}
output.append(decoded)
return output
b = deepcopy(a)
b["metricHeaders"].reverse()
b["rows"][0]["metricValues"].reverse()
assert decode(a) == decode(b)
assert decode(a)[0]["averageSessionDuration"]["value"] == 1.5
zero = deepcopy(a)
zero["rows"][0]["metricValues"] = [{"value": "0"}, {"value": "0"}]
assert all(cell["value"] == 0 for cell in decode(zero)[0].values())
bad = deepcopy(a)
bad["rows"][0]["metricValues"].pop()
try:
decode(bad)
except AssertionError:
pass
else:
raise AssertionError("Missing metric must fail")The output retains type metadata beside the parsed value. Do not discard that metadata and later label every numeric column milliseconds. Keep dimension headers and dimension values under the same alignment discipline in the actual consumer; the code narrows itself to metric decoding deliberately.
Distinguish Zero, Missing And Invalid
A returned value string “0” is different from an absent value key. An empty string or an unparseable number is another state requiring a failure or documented source treatment. Do not catch all decoding exceptions and return zero.
Keep integer parsing direct. Converting a large integer through a floating-point value can lose precision before conversion back to an integer. For currency and specialized types not implemented here, add a deliberate representation and unit policy rather than expanding a catch-all branch.
The worked-number review helps check those transformations. Correct parsing still cannot decide whether the metric is appropriate for the business question.
Preserve Identity Through Reporting Changes
Store the request definition, response headers, source retrieval time and decoder revision. If a requested metric changes, the report consumer should recognize the new name rather than continue applying a familiar dashboard heading to an unfamiliar column.
A metric used only as a filter or expression may not produce a visible column under the MetricHeader documentation. Do not manufacture a missing column because a field appeared somewhere in the request. Use the actual returned headers and required output contract together.
The data-quality guide covers a separate layer: sampling, thresholds and reporting identity. A correctly decoded value can still carry those interpretation limits. Keep them beside the decoded report rather than assuming a successful parser removes uncertainty.
Validate The Required Output Before Handoff
The fixture deliberately requires the two named metric headers. A response containing only one of them is not equivalent merely because its remaining row values align. The consumer must validate its expected output fields as well as the internal shape. In a production consumer, derive that expectation from the saved approved request, not from a stale dashboard assumption or the fixed names in this teaching example.
When a downstream display converts seconds to milliseconds, preserve the source metric and type alongside a clearly named derived value. For the fictional 1.5-second entry, that derived value is 1500 milliseconds. Do not relabel the original response as though the API supplied milliseconds. If a CSV export flattens these fields, provide a data dictionary that retains the unit and transformation revision.
Do not average already-averaged rows merely because every decoded duration is numeric. Aggregation requires the appropriate denominator and source meaning; this decoder does not supply them. A correctly parsed result should survive handoff without gaining an unsupported total, rate or business interpretation.
Save A Decoder Acceptance Receipt
Record both original and reordered fixtures, expected named outputs, zero and missing cases, unsupported-type behavior and executed assertions. The release ledger should identify changes that affect report interpretation.
Approve when row values remain attached to their actual headers and units through the tested changes, and invalid shape is reported rather than coerced. This establishes a bounded consumer contract for public-content analytics. It does not establish query compatibility, source completeness or a real change in acquisition performance.
