How to Convert a CSV into JSON using Python or Java. The CSV Is Representation of a Nested JSON (Containing Array of JSON Objects and Nested Objects)



I get a CSV file like this:

attrib1_x , attrib1_y , attrib1_z_0_p , attrib1_z_0_c , attrib1_z_1_p , attrib1_z_1_c , attrib2_R , attrib2_K , attrib3

1 , 2 , 100 , 200 , 500 , 600 , 222 , 320 ,hello

The csv represents a JSON as follows:



So basically here I get the above CSV, and need to convert it to the JSON structure shown

. Not sure how to do it. is there any library (Python/Java) which can help me with this?

If any solution/suggestion with different CSV header available that will also work. I can ask the team to provide me the CSV with different header names to represent the nested / arrays.


The first row of your CSV contains field names (which uses the underline to show the hierarchical relationship) and detail data starts from the second line, and you need to transform the CSV to JSON format. Here the difficulty is dynamic parsing. It will involve grouping, recursion, loop, conditional judgment and string concatenation. The code will be rather lengthy if you try to do this in Java.

Try using SPL, the open-source Java package, to do this. It is easy and five lines of code are enough:








func   recurse(AA)

>if(ifn==false,B1=left(B1,-i)/"{}"/right(B1,i),(B1=replace(B1,"{}","[]"),B1=left(B1,-i)/"{}"/right(B1,i),ifn=false)),i+=1,,(ifn=true,func(recurse,~.(~.m(2:)))),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:)))))))






SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as recurse.splx and invoke it in a Java application as you call a stored procedure:


con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call recurse()");

View SPL source code.