解析 Json 数组存入 CSV 文件

【问题】

I am trying to create a CSV file from a dynamically generated JSON array. For example:

“People” :

[{“name” : “Bob”, “age” : 5},

 {“dob” : “5/2/4”, “name” : “Alice”},

 {“name” : “George”}]

would create the csv file

name, age, dob

Bob, 5,

Alice, , 5/2/4

George, ,

As you can see, I need to create a column for every field in the JSON array. The order of each key-value pair in the JSON array is random. I also do not know name of the keys beforehand. Don’t worry about the “People” field, there will only be one array in each JSON. (This will most be the CSV name).

I have tried using theJackson CSV library but this requires me to create a pre-defined POJO as a middle tier (JSON -> POJO -> CSV). As far as I know, Java does not allow me to dynamically generate a class’ member variables at run time, so this method will not work. Same withGSON.

I will need to do this over a large data set, so efficiency would be pretty key. What would be the best way to approach this problem?

【回答】

用 java 解析这类结构不定的 json 字串有些麻烦,SPL 就很简单:

A
1 =file(“d:\\data.json”).read()
2 =json(A1).People
3 =file(“D:\\result.csv”).export@c(A2)

运行结果:

A1:读取 json 内容并返回成序表

A2:读取序表

A3:将续表输出到 csv 文件