11.6 Recursively concatenate field values
The following JSON file records numbers of confirmed cases of COVID-19 in different regions of the world at a certain time, and we want to find the total number worldwide. Below is part of the JSON file:
[
{Region:"USA",Confirmed:[
{Region:"California",Confirmed:3671902},
{Region:"New York",Confirmed:1139740},
{Region:"Virginia",Confirmed:620801},
{Region:"Florida",Confirmed:2064525},
…
]},
{Region:"Brazil",Confirmed:[…]},
{Region:"India",Confirmed: […]},
{Region:"France",Confirmed: […]}
…
]
Some countries have the country-level numbers, some have state/province-level numbers and some offer city-level numbers. In this case we cannot loop through field values and simply sum them. Instead, we need recursive sum. SPL has A.conj@r() function to concatenate members of sequences recursively.
SPL script:
A | |
---|---|
1 | =json(file(“COVID-19.json”).read()) |
2 | =A1.field@r(“Confirmed”) |
3 | =A2.conj@r().sum() |
A1 Import the JSON file.
A2 Use A.field@r() function to get all Confirmed field values recursively.
A3 Use A.conj@r() function to concatenate all confirmed cases and perform sum.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL