JSON数组到CSV的转换
我想把JSON转换成CSV。我正在使用list函数来满足这个目的。 但我并没有得到JSON数组想要的输出。请查找我正在使用的示例JSON和list函数: JSON文档示例:JSON数组到CSV的转换,json,ibm-cloud,export-to-csv,cloudant,Json,Ibm Cloud,Export To Csv,Cloudant,我想把JSON转换成CSV。我正在使用list函数来满足这个目的。 但我并没有得到JSON数组想要的输出。请查找我正在使用的示例JSON和list函数: JSON文档示例: { "NAME": "Viv", "EMAIL": "lo", "PUBLIC_OFFICIALS_CONTACTED": [{ "NAME_PUBLIC_OFFICIAL": [ "ff"], "TITLE_PUBLIC_OFFICIAL": ["ff"] }
{
"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的列表函数
电流输出:
预期产出:
CSV是一个单一的、扁平的每行值列表和一行标题。本问题中共享的预期输出与CSV不兼容-有必要通过解压嵌套的数据结构“扁平化”JSON,并将其转换为一个扁平的数据层次结构,然后成为CSV。尝试用搜索引擎搜索“JSON到CSV”以获取一些示例-希望有帮助 我参考了这一点,并尝试了以下方法: jsonflatter.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);
}
}
}
}
import org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.util.*;
公共类JSONFlatter{
公共映射解析(JSONObject JSONObject)抛出JSONException{
Map flatJson=new HashMap();
展平(jsonObject,flatJson,“”);
返回flatJson;
}
公共列表解析(JSONArray JSONArray)抛出JSONException{
List flatJson=newArrayList();
int length=jsonArray.length();
for(int i=0;i
类:它将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;
}
}
import org.apache.commons.lang.StringUtils;
导入java.io.BufferedWriter;
导入java.io.FileNotFoundException;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.util.*;
公共类CSV编写器{
public void writeAsCSV(List flatJson,String fileName)引发FileNotFoundException{
Set headers=collectHeaders(flatJson);
字符串输出=StringUtils.join(headers.toArray(),“,”)+“\n”;
for(映射:flatJson){
输出=输出+GetCommaseOperatedRow(头,映射)+“\n”;
}
writeToFile(输出,文件名);
}
私有void writeToFile(字符串输出,字符串文件名)引发FileNotFoundException{
BufferedWriter=null;
试一试{
writer=newbufferedwriter(newfilewriter(fileName));
writer.write(输出);
}捕获(IOE异常){
e、 printStackTrace();
}最后{
关闭(作者);
}
}
私有无效关闭(BufferedWriter){
试一试{
if(writer!=null){
writer.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
私有字符串GetCommaseOperatedRow(设置标题、映射){
列表项=新建ArrayList();
for(字符串标题:标题){
字符串值=map.get(header)=null?”:map.get(header.replace(“,”,”);
增加(价值);
}
返回StringUtils.join(items.toArray(),“,”);
}
私有集合集合头(列表){
Set headers=new TreeSet();
for(映射:flatJson){
headers.addAll(map.keySet());
}
返回标题;
}
}
杰森托克
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");
}
}