How to Convert CSV To Nested JSON in Java
Question
Source: https://stackoverflow.com/questions/58859344/how-to-convert-csv-to-nested-json-in-java
I have a csv file of following format:
A_aa,A_ab,A_ac,A_ad,B_BB_ba,B_BB_BBB_bb
1,2,3,4,5,6
And I want to convert it into the following nested JSON:
{
'A':{
'aa' : '1',
'ab' : '2',
'ac' : '4',
'ad' : '5',
}
'B':{
'BB':{
'ba' : '5',
'BBB':{
'bb' : '6'
}
}
}
}
Answer
The CSV file’s first row contains field headers (the underline is used to represent the hierarchical relationship. Detail data begins from the second row. Your need is to transform the CSV to JSON. The difficulty lies in dynamic parsing because it involves grouping, recursion, loop, conditional judgment and string concatenation. The code will be really lengthy if you try to achieve your task using Java.
It is easy to achieve this using SPL, the open-source Java package. Five lines of code are enough:
A |
B |
|
1 |
=file("json.csv").import@cw() |
|
2 |
=i=0,A1(1).(~.split("_")).(~|A1(2)(#)).(~.run(~="\""/~/"\"")) |
|
3 |
func recurse(AA) |
>B1=left(B1,-i)/"{}"/right(B1,i),i+=1,AA.group(~(1)).(if(~.len()==1 && ~(1).len()==2,B1=left(B1,-i)/~(1).concat(":")/right(B1,i),(B1=left(B1,-i)/~(1)(1)/":"/right(B1,i),func(recurse,~.(~.m(2:)))))) |
4 |
=func(recurse,A2) |
|
5 |
=replace(replace(B1,"\"\"","\",\""),"}\"","},\"") |
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as recurse.splx and invoke it in Java as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call recurse()");
st.execute();
…
View SPL source code.
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
Chinese version