解析多层 json 存入 CSV 文件

【问题】
I’m trying to export JSON to a csv file, but I can’t seem to find a step by step tutorial. I’m wondering if anyone can help me?

I have parsed my JSON file using the approach discribed in thislink.

It works now, but I still need to figure out how to export the parsed data into a CSV file..

You can find in the link below the JSON file I parsed, I just have to figure out how to export:

“attributeName”: “Description”,  
“attributeValue”: ""  
“attributeName”: “Functional Area”,  
“attributeValue”: “TECH”
public static void main(String[] args){
  String json=“{\“content\”: [  {\“a\”:{ \“b\” : \“abcd\”, \“c\” : \“bcd\”},\“ab\” : \“123\”,\“abc\”:{\“id\” : \“12345\”, \“name\” : \“abcde\”},\“cd\”: \“afsf\”},{\“a\”:{\“b\” : \“abcd\”,  \“c\” : \“bcd\”},\“ab\” : \“123\”,\“abc\”:{\“id\” : \“12346\”,\“name\” : \“abcde\”},\“cd\”: \“afsf\”}]}”;
        JSONObject jsonObject = new JSONObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray(“content”);
        for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject objects = jsonArray.getJSONObject(i);

                    String[] elementNames = JSONObject.getNames(objects);

                       for (String elementName : elementNames)

                          {

                           if(elementName.equalsIgnoreCase(“abc”)){

                           JSONObject value = objects.getJSONObject(elementName);

                           String[] elementList = JSONObject.getNames(value);

                            for(String j:elementList){

                                if(j.equalsIgnoreCase(“id”)){

                                System.out.println(value.getString(“id”));  

                                }

                            }

                          }

                          }
        }
    }
Output:-
12345
12346

【回答】
你希望取出多层 json 里的 id\name 字段,以上代码但太过复杂。SPL 实现了完整功能,包括:解析 json,读出 id\name,导为 csv。代码简单多了:

A
1 =file(“d:\\source.json”).read()
2 =json(A1).content.(abc)
3 =file(“d:\\result.csv”).export@c(A2)

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

运行结果:

A1:读取 json 内容并返回字符串

A2:生成符合条件的序表

A3:将序表输出到 csv 文件