多层 JSON 转换成 CSV

【问题】

This is how my json looks like:

{

  “data” :

    [

       { “f1” : “v1”,

         “f2” : “v2”,

         “group” : [

              { “f3” : “x1”,

                “f4” : “y1”,

                “f5” : “z1”

              },

              { “f3” : “x1”,

                “f4” : “y2”,

                “f5” : “z2”

              },

              { “f3” : “x2”,

                “f4” : “y3”,

                “f5” : “z3”

              }]

       },

       { “f1” : “vf1”,

         “f2” : “vf2”,

         “group” : [

              { “f3” : “x1”,

                “f4” : “y1”,

                “f5” : “z1”

              },

              { “f3” : “x1”,

                “f4” : “y2”,

                “f5” : “z2”

              },

              { “f3” : “x1”,

                “f4” : “y3”,

                “f5” : “z3”

              }]

       }

    ]

}

I am using the following code to convert it into Csv:

JSONArray array = (JSONArray)json.get(“data”);

String dataCSV = CDL.toString(array);

But this code is giving me “null” in dataCSV.

I want to know why it is getting null in dataCSV and also please provide a solution on “How to get CSV from this JSON ?” or “from a POJO Class to CSV”.

Thanks in advance

【回答】

f1,f2 是上级(相当于分组字段),需要重复拼到下级(相当于组内明细),也就是将多层 json 转为单层(二维表),这样才能输出为 csv。用 SPL 实现这个过程比较简单:

A
1 =file(“d:\\data.json”).read()
2 =json(A1).dat
3 =A2.news(group;A2.f1,A2.f2,f3,f4,f5)
4 =file(“d:\\result.csv”).export@c(A3)

A3 运行结果:

A1:读取 JSON

A2:解析 json 获得 data 节点

A3:提取所需字段生成新序列

A4 输出到 csv 文件

这段代码可以方便地集成进 Java,参考【Java 如何调用 SPL 脚本】。