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)

 

问题

https://stackoverflow.com/questions/66796180/how-to-convert-a-csv-into-json-using-python-or-java-the-csv-is-representation-o

I get a csv file like :

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 like below.


{
"attrib1":{
"x":1,
"y":2,
"z":[{"p":100,"c":200},{"p":500,"c":600}]
},
"attrib2":{"R":222,"K":320},
"attrib3":"hello"
}

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.

解答

csv文件中的第一行是字段名(用下划线表示了层次关系),第 2 行是数据,需要把csv 转成 json 格式。难点在于动态解析,需要用到分组、递归、循环、条件判断与字符串拼接。用 Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要 5 行:


A

B

1

=file("data.csv").import@cw()

2

=i=0,ifn=false,A1(1).(~.split@p("_")).(~|A1(2)(#)).(~.(~=if(ifstring(~),"\""/~/"\"",~)))

3

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,AA.group(~(1)).(if(ifnumber(~(1)(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:)))))))

4

=func(recurse,A2)

5

=replace(replace(replace(B1,",}","}"),"}{","},{"),"}\"","},\"")

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为 recurse.splx,在 Java 中以存储过程的方式调用脚本文件:

Class.forName("com.esproc.jdbc.InternalDriver");

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

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

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集