From a keyed JSON record to a dashboard that cites its source
The shape you get, and the shape you need
{
"data": {
"undata/sdg/VC_DTH_TOTN": { ← keyed by variable
"country/COD": { ← keyed by entity
"facet": "12883393359649061195",
"obsCount": 10,
"series": [
{ "date": "2015", "value": 945 },
{ "date": "2016", "value": 836 }
]
},
"country/SSD": { "...": "..." }
}
},
"facets": { ← the meaning lives here
"12883393359649061195": {
"provenanceUrl": "https://unstats.un.org/sdgs/dataportal",
"provenanceId": "undata/p/SDG",
"observationPeriod": "P1Y",
"unitDisplayName": "Number"
}
}
}Two of those levels are keyed by data, not by schema — the column names are the identifiers you asked for. No BI tool infers that. You have to turn keys into rows explicitly, which in Power Query is Record.ToTable and in every scripting language is a loop over the items.
The target. One row per observation, with the facet joined on so the unit and the source travel with the number rather than being looked up later by a human.
| variable | entity | date | value | unit | source |
|---|---|---|---|---|---|
| …/VC_DTH_TOTN | country/COD | 2015 | 945 | Number | unstats.un.org |
| …/VC_DTH_TOTN | country/COD | 2016 | 836 | Number | unstats.un.org |
| …/VC_DTH_TOTN | country/SSD | 2015 | 2418 | Number | unstats.un.org |
| …/VC_DTH_TOTN | country/SSD | 2016 | 2807 | Number | unstats.un.org |
Long, not wide. Do not pivot years into columns in the extract: both tools pivot for display far better than they unpivot for analysis, and a wide table has to be rebuilt every time a new year is published.
A scenario, before the reference material
Somebody asks
“Can I get conflict deaths against GDP per capita, as a scatter?”
A colleague preparing a background note, who has seen the chart elsewhere
GDP per capita, current US dollars
undata/unicef/SPP_GDPPC- Found by
- Search, read down to the eighth result
- Covers
- 210 countries · 2024 for every country — a genuine cross-section
Conflict-related deaths per 100,000 population
undata/sdg/VC_DTH_TOTR- Found by
- Four graph walks down the SDG framework
- Covers
- 14 countries · 2022, 2023 and 2024
The call this scenario needs
GET /core/api/v2/observation
One value per place across a whole region. The containment expression is evaluated inside the graph, so this is one request rather than a loop over country codes.
let
Base = "https://unsd-datacommons.gcp.un-icc.cloud",
Parent = "Earth",
fnLatest = (Variable as text) as table =>
let
Path = "core/api/v2/observation?date=" & Uri.EscapeDataString("LATEST")
& "&variable.dcids=" & Uri.EscapeDataString(Variable)
& "&entity.expression=" & Uri.EscapeDataString(Parent & "<-containedInPlace+{typeOf:Country}")
& "&select=date&select=value&select=entity&select=variable",
Response = Json.Document(Web.Contents(Base, [RelativePath = Path])),
// byVariable -> byEntity -> orderedFacets[] -> observations[].
// Both of the first two levels are keyed by data, so both need
// Record.ToTable rather than an expand.
ByVariable = Record.ToTable(Response[byVariable]),
WithRows = Table.AddColumn(ByVariable, "rows", each Record.ToTable([Value][byEntity])),
Flat = Table.ExpandTableColumn(
Table.RemoveColumns(WithRows, {"Name", "Value"}),
"rows", {"Name", "Value"}, {"entity", "block"}),
// A place the graph knows but has no value for comes back as an
// empty record. Absent is not zero: drop the row, never fill it.
WithObs = Table.AddColumn(Flat, "obs", each
let Ranked = Record.FieldOrDefault([block], "orderedFacets", {})
in if List.Count(Ranked) = 0 then null else Ranked{0}[observations]{0}),
HasData = Table.SelectRows(WithObs, each [obs] <> null),
Shaped = Table.AddColumn(
Table.AddColumn(HasData, "year", each [obs][date], type text),
"value", each [obs][value], type number)
in
Table.SelectColumns(Shaped, {"entity", "year", "value"}),
X = Table.RenameColumns(fnLatest("undata/unicef/SPP_GDPPC"),
{{"year", "year_x"}, {"value", "value_x"}}),
Y = Table.RenameColumns(fnLatest("undata/sdg/VC_DTH_TOTR"),
{{"year", "year_y"}, {"value", "value_y"}}),
// An inner join across two agencies keeps only the places that have
// both. Print the three counts before you plot: the join is where
// countries disappear, and it never says so.
Joined = Table.NestedJoin(X, {"entity"}, Y, {"entity"}, "y", JoinKind.Inner),
Points = Table.ExpandTableColumn(Joined, "y", {"year_y", "value_y"}),
// Carry the three counts into the model so a card can show them. A scatter
// that quietly lost 196 of its 210 countries must say so on the page.
Counted = Table.AddColumn(Points, "countries_x", each Table.RowCount(X), Int64.Type),
Both = Table.AddColumn(Counted, "countries_both", each Table.RowCount(Points), Int64.Type)
in
BothWhat the data does that the question did not expect
210 countries, 14 countries, and every point you plot is a country at war
GDP per capita returns 210 countries. The conflict death rate returns 14. The inner join keeps 14, and those 14 are Afghanistan, the Central African Republic, DR Congo, Ethiopia, Iraq, Lebanon, Libya, Mali, Myanmar, the Palestinian Territories, the Philippines, South Sudan, Syria and Ukraine. Norway, Costa Rica and Japan are not zero on this indicator — they are absent from the response entirely, because a country with no conflict files no conflict-death return. A scatter of these two series cannot say anything about whether conflict and income are related across countries, because every peaceful country has been removed from the sample before the chart is drawn. The chart would not be imprecise. It would be answering a different question from the one asked.
What this means for the report, specifically
- Use JoinKind.Inner and mean it. A left join here would give you 210 rows, 196 of them with a blank y value, and a scatter visual silently plots nothing for those. You would see fourteen points either way and have no idea the other 196 existed.
- Put the counts on the canvas. The M in the tab above carries
countries_xandcountries_bothinto the model for exactly this reason. Two cards and a subtitle — “14 of 210 countries have both” — turn a misleading chart into an honest one without changing a single data point. - Log the income axis. The x values run from 353 to 7,330 dollars. On a linear axis eleven of the fourteen points pile into the left quarter of the plot. Power BI sets this per axis under Format → X axis → Scale type.
- Do not add a trend line. Power BI offers one on every scatter and it will happily fit fourteen points that were selected by the join. The R² it prints is a statement about the join, not about the world.
The same guard, as a measure
If you would rather the report told you than remembered for you, this reads the two counts out of the model and writes the caption itself. Put it in the scatter visual's title.
Scatter title =
VAR Plotted = DISTINCTCOUNT ( Points[entity] )
VAR Available = MAX ( Points[countries_x] )
RETURN
"Conflict deaths and income — "
& Plotted & " of " & Available
& " countries have both indicators"The full discovery trail for this one — including the two searches that failed and the four graph walks that did not — is on the scenarios page.
Which endpoint your dashboard should call
| Endpoint | Use it when | Returns |
|---|---|---|
/api/observations/series | You know the countries and want the full history — the usual case for a trend page. | data → variable → entity → series[] |
/core/api/v2/observation | You want one value per country across a whole region, for a ranking or a map, without listing country codes. | byVariable → byEntity → orderedFacets[] → observations[] |
/api/place/name | Always, at the end. It turns country/SSD into South Sudan so an axis label is readable. | a flat record of dcid → name |
The query cookbook has these as curl, with the containment-expression grammar explained. This page assumes you have picked one and now need it inside a tool.
Power BI — step 1, the request
let
// ── edit these three, nothing else ───────────────────────────────
Base = "https://unsd-datacommons.gcp.un-icc.cloud",
Variables = {"undata/sdg/EG_ACS_ELEC", "undata/sdg/IT_USE_ii99"},
Entities = {"country/BGD", "country/ETH", "country/IND", "country/KEN"},
// ─────────────────────────────────────────────────────────────────
// POST, because the payload is two JSON arrays. Web.Contents turns the
// request into a POST as soon as Content is present.
//
// Keep Base a literal string and put the path in RelativePath. That is
// what lets the Power BI Service recognise a fixed data source and
// refresh it on a schedule; a URL assembled with & becomes a "dynamic
// data source" and scheduled refresh refuses it.
Response = Json.Document(
Web.Contents(Base, [
RelativePath = "api/observations/series",
Headers = [#"Content-Type" = "application/json"],
Content = Json.FromValue([variables = Variables, entities = Entities])
])
)
in
ResponseWhen it asks how to sign in
Choose Anonymous, at the level of the base URL. There is no API key and no account. If you also see a privacy-level prompt, set this source to Public — it is published official statistics, and leaving it at Private is what later produces a Formula.Firewall error when you combine it with anything else.
The same M works in Excel
Data → Get Data → From Other Sources → Blank Query. Power Query is the same engine in both, so a colleague without a Power BI licence can run the whole of this page in Excel and hand you the workbook.
Power BI — step 2, the cleaning
// ── keys into rows ───────────────────────────────────────────────
// data is a record keyed by variable, holding records keyed by entity.
// Record.ToTable is the move that makes dynamic keys into data.
ByVariable = Table.RenameColumns(Record.ToTable(Response[data]), {{"Name", "variable"}}),
AddEntity = Table.AddColumn(ByVariable, "entities", each Record.ToTable([Value])),
DropRecord = Table.RemoveColumns(AddEntity, {"Value"}),
ByEntity = Table.ExpandTableColumn(
DropRecord, "entities", {"Name", "Value"}, {"entity", "block"}),
// Each block holds the observations plus the facet id that attributes them.
AddFacetId = Table.AddColumn(ByEntity, "facet_id",
each Record.FieldOrDefault([block], "facet", null), type text),
AddObs = Table.AddColumn(AddFacetId, "obs",
each Table.FromRecords(Record.FieldOrDefault([block], "series", {}))),
// An entity with no data comes back with an empty series. Dropping the row
// is deliberate: a missing row draws as a gap, a zero draws as a
// measurement nobody took. Never fill this with 0.
HasData = Table.SelectRows(AddObs, each Table.RowCount([obs]) > 0),
DropBlock = Table.RemoveColumns(HasData, {"block"}),
Observations = Table.ExpandTableColumn(
DropBlock, "obs", {"date", "value"}, {"date", "value"}),
// date stays text on purpose. It is "2024", and occasionally "2024-06".
// A real date column would invent a day that nobody measured; year is the
// only part that is safe to make a number.
Typed = Table.TransformColumnTypes(
Observations, {{"date", type text}, {"value", type number}}),
AddYear = Table.AddColumn(Typed, "year", each Int64.From(Text.Start([date], 4)), Int64.Type),
// ── the facets, where the meaning lives ──────────────────────────
// Record.FieldOrDefault rather than Table.ExpandRecordColumn, because not
// every facet carries every field — HDI has no unitDisplayName at all, and
// expanding a field that is absent puts errors in the cells.
FacetRows = Table.RenameColumns(Record.ToTable(Response[facets]), {{"Name", "facet_id"}}),
FacetUrl = Table.AddColumn(FacetRows, "source_url",
each Record.FieldOrDefault([Value], "provenanceUrl", null), type text),
FacetProv = Table.AddColumn(FacetUrl, "provenance",
each Record.FieldOrDefault([Value], "provenanceId", null), type text),
FacetUnit = Table.AddColumn(FacetProv, "unit",
each Record.FieldOrDefault([Value], "unitDisplayName", null), type text),
FacetPer = Table.AddColumn(FacetUnit, "period",
each Record.FieldOrDefault([Value], "observationPeriod", null), type text),
Facets = Table.SelectColumns(
FacetPer, {"facet_id", "source_url", "provenance", "unit", "period"}),
Joined = Table.NestedJoin(AddYear, {"facet_id"}, Facets, {"facet_id"}, "f", JoinKind.LeftOuter),
WithSource = Table.ExpandTableColumn(
Joined, "f", {"source_url", "provenance", "unit", "period"}),Power BI — step 3, names and a retrieval stamp
// ── readable place names ─────────────────────────────────────────
NameResponse = Json.Document(
Web.Contents(Base, [
RelativePath = "api/place/name",
Headers = [#"Content-Type" = "application/json"],
Content = Json.FromValue([dcids = Entities])
])
),
NameRows = Table.RenameColumns(Record.ToTable(NameResponse), {{"Name", "entity"}, {"Value", "place"}}),
NameTyped = Table.TransformColumnTypes(NameRows, {{"entity", type text}, {"place", type text}}),
Named = Table.ExpandTableColumn(
Table.NestedJoin(WithSource, {"entity"}, NameTyped, {"entity"}, "n", JoinKind.LeftOuter),
"n", {"place"}),
// ── stamp the pull ───────────────────────────────────────────────
// Computed once as a step, not inside the each lambda — in there it is
// re-evaluated per row and you get a column of near-identical timestamps.
Retrieved = DateTimeZone.UtcNow(),
Stamped = Table.AddColumn(Named, "retrieved_at", each Retrieved, type datetimezone),
Final = Table.SelectColumns(Stamped, {
"variable", "entity", "place", "date", "year", "value",
"unit", "period", "provenance", "source_url", "retrieved_at"})
in
FinalWhy the name lookup is in this query and not its own
The obvious design is a second query that reads the distinct entities out of the first and posts them to /api/place/name. Power Query refuses it: “Query references other queries or steps, so it may not directly access a data source.” Feeding one query's output into another query's web request is exactly what the privacy firewall blocks. Because Entities is a literal list in this query, posting it here is not a cross-query reference and the firewall has nothing to object to. Splitting into dimension tables afterwards with Reference is fine — it is only the web call that is constrained.
Power BI — step 4, the model
The star
DimPlace DimIndicator
entity (key) variable (key)
place short_name
region unit
\ /
\ /
FactObservation
variable, entity, year,
value, facet_id
|
DimSource
facet_id (key)
provenance, source_url, periodBuild the dimensions by right-clicking the finished query → Reference, keeping the relevant columns, then Remove Duplicates. Set each relationship to single-direction, one-to-many, from dimension to fact.
Latest value =
VAR LatestYear = MAX ( FactObservation[year] )
RETURN
CALCULATE (
SELECTEDVALUE ( FactObservation[value] ),
REMOVEFILTERS ( FactObservation[year] ),
FactObservation[year] = LatestYear
)Vintage spread (years) =
VAR YearPerEntity =
ADDCOLUMNS (
VALUES ( FactObservation[entity] ),
"@Year", CALCULATE ( MAX ( FactObservation[year] ) )
)
RETURN
MAXX ( YearPerEntity, [@Year] ) - MINX ( YearPerEntity, [@Year] )Put the second measure on the page, not in a comment
A “latest available” map looks like a cross-section and usually is not. The homicide ranking in the peace case spans fifteen reference years; the HDI ranking in the development case spans none. Same query, different data. A card showing Vintage spread beside the map tells your reader which of the two they are looking at, and costs one visual.
Tableau — pick a route before you write anything
- 1
A tidy CSV on a schedule — start here
Something writes one flat file; Tableau connects to it as a text file, a Google Sheet, or a published URL. Unglamorous, works everywhere, survives you leaving the office. This is the right answer for almost every UN team.
- 2
A .hyper extract, published to Tableau Server or Cloud
Same idea with a faster file. A scheduled job writes the extract with the tableauhyperapi package and publishes it with tableauserverclient. Worth it when the extract is large or many workbooks share it.
- 3
Tableau Prep with a Script step
Prep can call a Python function through TabPy. Reasonable if your organisation already runs a TabPy server; not worth standing one up for this alone, and Prep flows are harder to review than a twelve-line script.
- 4
A Web Data Connector 3.0
The only route that queries the API live from Tableau. You build it with the Tableau Connector SDK and host it yourself, then keep it working across Tableau versions. For one team that is more maintenance than a scheduled file, and the data changes annually.
What not to do: point Tableau's JSON connector at the raw response
It will open the file, and it will produce a column per identifier — data.undata/sdg/EG_ACS_ELEC.country/BGD.series.0.value and one more for every observation. The schema then changes the next time you ask for a different country, which breaks every calculated field built on it. Flatten first, always.
Tableau — making the rectangle
curl -s -X POST 'https://unsd-datacommons.gcp.un-icc.cloud/api/observations/series' \
-H 'Content-Type: application/json' \
-d '{"variables":["undata/sdg/EG_ACS_ELEC"],"entities":["country/BGD","country/ETH","country/IND"]}' \
| jq -r '
.facets as $f
| ["variable","entity","year","value","unit","source"],
( .data | to_entries[] as $v
| $v.value | to_entries[] as $e
| ($f[$e.value.facet] // {}) as $facet
| ($e.value.series // [])[]
| [ $v.key, $e.key, .date, .value,
($facet.unitDisplayName // ""),
($facet.provenanceUrl // "") ] )
| @csv' > un-indicator.csvVerified against the live platform: 75 rows for those three countries. The // [] and // "" fallbacks are what stop a country with no data from aborting the whole file.
For anything beyond one indicator, use the Python helper on the Python, R & Julia page and finish with frame.to_csv(…, index=False). It already handles the empty-series case, joins the facets and adds the place names.
To write a .hyper extract instead, the same frame goes straight into it:
import pantab # pip install pantab
pantab.frame_to_hyper(
frame, "un-indicator.hyper", table="observations"
)pantab is a thin wrapper over the official tableauhyperapi; use the latter directly if you need control over column types. Publish with tableauserverclient from the same script.
Whichever route, schedule it the way the self-refreshing chart recipe does — a weekly cron or GitHub Action is ample for data that is published annually.
Tableau — three things to set up in the workbook
Year is a dimension, not a date
Tableau will happily cast "2015" to 1 January 2015 and then offer you month and quarter. Those do not exist. Convert year to a whole-number dimension and leave date as a string.
The source belongs on the sheet
Add a calculated field — "Source: " + ATTR([provenance]) + ", retrieved " + STR([retrieved_at]) — and put it on Tooltip and in a caption. A dashboard gets screenshotted within a week; the caption is all that travels with it.
Guard the mixed vintage
An LOD makes it a number you can display: MAX({FIXED [Entity] : MAX([Year])}) − MIN({FIXED [Entity] : MAX([Year])}). If it is not zero, the map is not a cross-section, and the title should say so.
One licensing note: Tableau Public is free and publishes your workbook and its data publicly. That is fine for published UN statistics and not fine for a workbook that also holds internal figures — the same caution the charting tools page gives for Datawrapper and Flourish.
Five things that will bite a dashboard specifically
- 1
A gap filled to zero by the visual, not by you
Both tools offer to show missing values as zero on a line or in a matrix. On this data that turns "no survey was run" into "the value was nought". Turn it off in Format → Analytics, and in Tableau uncheck Show Missing Values.
- 2
A slicer that also filters the source caption
If the caption reads from the fact table, filtering to one country changes it. Put provenance in its own dimension table and let the caption measure read from there, so it keeps naming every agency in the report.
- 3
Scheduled refresh refusing a dynamic data source
It means the URL was built by string concatenation somewhere. Every web call must be Web.Contents(literal, [RelativePath = …]) for the Service to resolve it. This also rules out Power BI’s Python and R script sources, which need a personal gateway.
- 4
A total that is not a total
Summing a rate, or summing age bands that exclude the unknown category, produces a confident wrong number. Set the default aggregation on percentage and index columns to Average or Do Not Summarize the moment the table loads.
- 5
Two agencies, one chart, no label
The facet is what tells you a series changed source mid-way. Keep facet_id in the fact table even though nobody will look at it, and colour or annotate by provenance when a series has more than one.
What this page leaves you with
Record.ToTable in M, a loop over items everywhere else. Once that lands, the rest is ordinary table work.data; the unit, the period and the agency are in facets. A dashboard that drops them has lost the part a reader needs to check the figure.RelativePath and Content are not a style preference in Power BI — they are the difference between a report that refreshes on a schedule and one somebody has to open every Monday.