Convert Multilevel JSON to a CSV
【Question】
This is how my JSON looks like:
{
“data” :
[
{ “f1” : “v1”,
“f2” : “v2”,
“group” : [
{ “f3” : “x1”,
“f4” : “y1”,
“f5” : “z1”
},
{ “f3” : “x1”,
“f4” : “y2”,
“f5” : “z2”
},
{ “f3” : “x2”,
“f4” : “y3”,
“f5” : “z3”
}]
},
{ “f1” : “vf1”,
“f2” : “vf2”,
“group” : [
{ “f3” : “x1”,
“f4” : “y1”,
“f5” : “z1”
},
{ “f3” : “x1”,
“f4” : “y2”,
“f5” : “z2”
},
{ “f3” : “x1”,
“f4” : “y3”,
“f5” : “z3”
}]
}
]
}
I am using the following code to convert it into CSV:
JSONArray array = (JSONArray)json.get(“data”);
String dataCSV = CDL.toString(array);
But this code is giving me “null” in dataCSV.
I want to know why it is getting null in dataCSV and also please provide a solution on “How to get CSV from this JSON ?” or “from a POJO Class to CSV”.
Thanks in advance.
【Answer】
f1 and f2 are the first level (which is equivalent to a grouping expression). They need to union with its next level of data (which is equivalent to detailed data in each group). The process is converting multilevel JSON data to a single level data (2D table) to be output to a CSV. It’s simple to do this in SPL (Structured Process Language):
A |
|
1 |
=file(“d:\\data.json”).read() |
2 |
=json(A1).dat |
3 |
=A2.news(group;A2.f1,A2.f2,f3,f4,f5) |
4 |
=file(“d:\\result.csv”).export@c(A3) |
A3’s result:
A1: Read in the JSON data.
A2: Parse JSON data to get the nodes.
A3: Get needed fields to generate a new sequence.
A4: Write data under the fields to a CSV file.
The SPL code can be easily integrated into a Java application. See How to Call an SPL Script in Java.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
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