2017-08-26 250 views
0

我想將JSON轉換爲CSV。我正在使用列表功能來達到目的。 但我沒有得到理想的JSON數組輸出。請找我現在用的樣品JSON和列表功能: 樣品JSON文件:JSON數組轉換爲CSV

{ 
"NAME": "Viv", 
"EMAIL": "lo", 

"PUBLIC_OFFICIALS_CONTACTED": [{"NAME_PUBLIC_OFFICIAL": [ "ff"], 
"TITLE_PUBLIC_OFFICIAL": ["ff"]}], 

"COMMUNICATION_TYPE": ["Meeting","Phone","Handout","Conference"], 

"NAMES_OF_OTHERS_FROM_XXX": [{"NAME_OF_OTHERS": ["ff"], 
"TITLE_OF_OTHERS": [ "ff"]}], 

"COMMUNICATION_BENEFIT": "Yes", 
"AFFILIATE_NAME": "name", 
"COMMUNICATION_ARRANGED": "Yes, arranged by you" 
} 

和列表功能,我使用的是:

function(head, req) { 
    var row, 
first = true; 

// output HTTP headers 
start({ 
headers: { 'Content-Type': 'text/csv' }, 
}); 

// iterate through the result set 
while(row = getRow()) { 

// get the doc (include_docs=true) 
var doc = row.doc; 

// if this is the first row 
if (first) { 

    // output column headers 
    send(Object.keys(doc).join(',') + 'n'); 
    first = false; 
} 

// build up a line of output 
var line = ''; 

// iterate through each row 
for(var i in doc) { 

    // comma separator 
    if (line.length > 0) { 
    line += ','; 
    } 

    // output the value, ensuring values that themselves 
    // contain commas are enclosed in double quotes 
    var val = doc[i]; 
    if (typeof val == 'string' && val.indexOf(',') > -1) { 
    line += '"' + val.replace(/"/g,'""') + '"'; 
    } else { 
    line += val; 
    } 
} 
line += 'n'; 

// send the line 
send(line); 
} 
}; 

隨函附上CSV輸出與預期輸出在excel中導出。 另外,在保存複選框值時存在問題。請幫我編寫上面的JSON轉換爲CSV的列表功能。 current outputexpected output

+0

您的具體問題是什麼?沒有人會爲你調試你的代碼,所以你將不得不顯示你做了什麼來解決你沒有說明的問題,以及你得到了什麼結果。請用這些細節更新問題的BODY。 https://stackoverflow.com/help/how-to-ask – jdv

回答

0

CSV是每行中單個的平坦值列表和一行標題。這個問題中共享的預期輸出與CSV不兼容 - 需要通過解包嵌套的數據結構來「扁平化」JSON,並將它們轉換爲可以變爲CSV的平面層次數據。嘗試使用搜索引擎搜索「JSON to CSV」以獲得一些示例 - 希望有所幫助!

0

我已經refered這個gitHUb link和嘗試以下操作:

JsonFlattener.class:這將讀取JSON字符串&提取關鍵&值

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.*; 
public class JsonFlattener { 
    public Map<String, String> parse(JSONObject jsonObject) throws JSONException { 
     Map<String, String> flatJson = new HashMap<String, String>(); 
     flatten(jsonObject, flatJson, ""); 
     return flatJson; 
    } 

    public List<Map<String, String>> parse(JSONArray jsonArray) throws JSONException { 
     List<Map<String, String>> flatJson = new ArrayList<Map<String, String>>(); 
     int length = jsonArray.length(); 
     for (int i = 0; i < length; i++) { 
      JSONObject jsonObject = jsonArray.getJSONObject(i); 
      Map<String, String> stringMap = parse(jsonObject); 
      flatJson.add(stringMap); 
     } 
     return flatJson; 
    } 

    public List<Map<String, String>> parseJson(String json) throws Exception { 
     List<Map<String, String>> flatJson = null; 
     try { 
      JSONObject jsonObject = new JSONObject(json); 
      flatJson = new ArrayList<Map<String, String>>(); 
      flatJson.add(parse(jsonObject)); 
     } catch (JSONException je) { 
      flatJson = handleAsArray(json); 
     } 
     return flatJson; 
    } 

    private List<Map<String, String>> handleAsArray(String json) throws Exception { 
     List<Map<String, String>> flatJson = null; 
     try { 
      JSONArray jsonArray = new JSONArray(json); 
      flatJson = parse(jsonArray); 
     } catch (Exception e) { 
      throw new Exception("Json might be malformed"); 
     } 
     return flatJson; 
    } 

    private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) throws JSONException { 
     int length = obj.length(); 
     for (int i = 0; i < length; i++) { 
      if (obj.get(i).getClass() == JSONArray.class) { 
       JSONArray jsonArray = (JSONArray) obj.get(i); 
       if (jsonArray.length() < 1) continue; 
       flatten(jsonArray, flatJson, prefix + i); 
      } else if (obj.get(i).getClass() == JSONObject.class) { 
       JSONObject jsonObject = (JSONObject) obj.get(i); 
       flatten(jsonObject, flatJson, prefix + (i + 1)); 
      } else { 
       String value = obj.getString(i); 
       if (value != null) 
        flatJson.put(prefix + (i + 1), value); 
      } 
     } 
    } 

    private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) throws JSONException { 
     Iterator iterator = obj.keys(); 
     while (iterator.hasNext()) { 
      String key = iterator.next().toString(); 
      if (obj.get(key).getClass() == JSONObject.class) { 
       JSONObject jsonObject = (JSONObject) obj.get(key); 
       flatten(jsonObject, flatJson, prefix); 
      } else if (obj.get(key).getClass() == JSONArray.class) { 
       JSONArray jsonArray = (JSONArray) obj.get(key); 
       if (jsonArray.length() < 1) continue; 
       flatten(jsonArray, flatJson, key); 
      } else { 
       String value = obj.getString(key); 
       if (value != null && !value.equals("null")) 
        flatJson.put(prefix + key, value); 
      } 
     } 
    } 
} 

CSVWriter.class:它改造了JSON字符串CSV文件

import org.apache.commons.lang.StringUtils; 
import java.io.BufferedWriter; 
import java.io.FileNotFoundException; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.*; 

public class CSVWriter { 
    public void writeAsCSV(List<Map<String, String>> flatJson, String fileName) throws FileNotFoundException { 
     Set<String> headers = collectHeaders(flatJson); 
     String output = StringUtils.join(headers.toArray(), ",") + "\n"; 
     for (Map<String, String> map : flatJson) { 
      output = output + getCommaSeperatedRow(headers, map) + "\n"; 
     } 
     writeToFile(output, fileName); 
    } 

    private void writeToFile(String output, String fileName) throws FileNotFoundException { 
     BufferedWriter writer = null; 
     try { 
      writer = new BufferedWriter(new FileWriter(fileName)); 
      writer.write(output); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      close(writer); 
     } 
    } 

    private void close(BufferedWriter writer) { 
     try { 
      if (writer != null) { 
       writer.close(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private String getCommaSeperatedRow(Set<String> headers, Map<String, String> map) { 
     List<String> items = new ArrayList<String>(); 
     for (String header : headers) { 
      String value = map.get(header) == null ? "" : map.get(header).replace(",", ""); 
      items.add(value); 
     } 
     return StringUtils.join(items.toArray(), ","); 
    } 

    private Set<String> collectHeaders(List<Map<String, String>> flatJson) { 
     Set<String> headers = new TreeSet<String>(); 
     for (Map<String, String> map : flatJson) { 
      headers.addAll(map.keySet()); 
     } 
     return headers; 
    } 
} 

JSONtoCSV.class:它將使用上述類來解析json &將關鍵值寫爲.csv文件

import java.util.List; 
import java.util.Map; 

public class JSONtoCSV { 
    public static void main(String[] args) throws Exception { 
     String jsonString = "{\n" + 
       "\"NAME\": \"Viv\",\n" + 
       "\"EMAIL\": \"lo\",\n" + 
       "\n" + 
       "\"PUBLIC_OFFICIALS_CONTACTED\": [{\"NAME_PUBLIC_OFFICIAL\": [ \"ff\"],\n" + 
       "\"TITLE_PUBLIC_OFFICIAL\": [\"ff\"]}],\n" + 
       "\n" + 
       "\"COMMUNICATION_TYPE\": [\"Meeting\",\"Phone\",\"Handout\",\"Conference\"],\n" + 
       "\n" + 
       "\"NAMES_OF_OTHERS_FROM_XXX\": [{\"NAME_OF_OTHERS\": [\"ff\"],\n" + 
       "\"TITLE_OF_OTHERS\": [ \"ff\"]}],\n" + 
       "\n" + 
       "\"COMMUNICATION_BENEFIT\": \"Yes\",\n" + 
       "\"AFFILIATE_NAME\": \"name\",\n" + 
       "\"COMMUNICATION_ARRANGED\": \"Yes, arranged by you\"\n" + 
       "}"; 

     JsonFlattener parser = new JsonFlattener(); 
     CSVWriter writer = new CSVWriter(); 

     List<Map<String, String>> flatJson = parser.parseJson(jsonString); 
     writer.writeAsCSV(flatJson, "C:/sample.csv"); 
    } 
}