How to Parse & Convert Multilevel JSONs into a Two-dimensional Table
【Question】
Is there any way to convert multiple JSONs into one csv?
My JSON file is like this:
{
“Title”: {
“name”:“ABC”,
“id”:“1”,
“job”:“Teacher”
},
“Circle”:{
“area”:“2R”
},
“Triangle”:{
“length”:“45”
}
}
If you will see, this JSON has 3 roots and different elements under each root. How to convert this JSON to CSV so that it can be opened in excel and can be viewed as follows:
Title
Name ABC
id 1
job Teacher
Circle
area 2r
Triangle
length 45
Can someone please suggest?
【Answer】
Your problem is to construct a two-dimensional table from multilevel JSON. As Java lacks of satisfactory methods of handling two-dimensional tables, it can only hard code the problem. That’s too complicated. An easier way of doing this is a SPL script, which can be conveniently called by Java. Below is the SPL code:
| A | ||
| 1 | =file(“d:\\data.json”).read() | |
| 2 | =json(A1) | |
| 3 | =A2.fno().(join@p((f=A2.field(~)).fname():key;f.array():value)) | |
| 4 | =A3.(~.record@i([A2.fname(#),null],1)) | |
| 5 | =A4.conj() | |
| 6 | =file(“D:\\result.csv”).export@c(A5) | 
Result of executing the SPL script:
  
 
A1: Read the JSON file as a string;
A2: Parse the string into a table sequence;
A3: Recombine field names and field values;
A4: Use null if a field name isn’t specified;
A5: split away each record and then concatenate them into a new sequence;
A6: Export the table into a CSV file.
 
SPL Official Website 👉 https://www.esproc.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.esproc.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/sxd59A8F2W
Youtube 👉 https://www.youtube.com/@esProc_SPL
 
            
        