JSON数组转换为CSV

时间:2017-08-26 13:38:08

标签: json ibm-cloud export-to-csv cloudant

我想将JSON转换为CSV。我正在使用列表功能来达到目的。 但我没有获得JSON数组的理想输出。请找到我正在使用的示例JSON和列表函数: 示例JSON文档:

{
"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);
}
};

请附上在excel中导出的csv输出和预期输出。 此外,保存复选框值存在问题。请帮我编写列表功能,将上述JSON转换为CSV。current output expected output

2 个答案:

答案 0 :(得分:0)

CSV是每行中单个,平面的值列表,以及一行标题。此问题中共享的预期输出与CSV不兼容 - 有必要通过解压缩嵌套数据结构并将其变为平坦的数据层次结构(然后可以变为CSV)来“展平”您的JSON。尝试使用搜索引擎搜索“JSON to CSV”以获取一些示例 - 希望有所帮助!

答案 1 :(得分:0)

我已提到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&amp;将密钥值写为.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");
    }
}
相关问题