首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Javascript将Json文件转换为CSV

用Javascript将Json文件转换为CSV
EN

Stack Overflow用户
提问于 2019-04-22 02:50:03
回答 1查看 324关注 0票数 0

我的项目有问题,我必须使用javascript将json文件转换为csv,但我不知道如何实现。

你能帮帮我吗?

我尝试过在这个站点上找到这个代码,但是它对我不起作用,因为它给我显示了这个,但是它显示了这个:

place,character,linename,warityu,warityu_kaigyo,elements,gojunelements,kanaelements [object Object],自,巻4:1オ03,false,false,[object Object],[object Object],[object Object] [object Object],陑,巻4:1オ03,false,false,[object Object],,[object Object]

编辑:这就是我想要的csv的结构: lineNumber,columnNumber,字符,linename,warityu,warityu_kaigyo,x,y,样式,标记,样式,标记,targetLenght,位置,positionText,样式,文本,

这是代码:

代码语言:javascript
复制
  "place" : {
    "lineNumber" : 3,
    "columnNumber" : 8
  },
  "character" : "自",
  "linename" : "巻4:1オ03",
  "warityu" : false,
  "warityu_kaigyo" : false,
  "elements" : [ {
    "position" : {
      "x" : 0.0,
      "y" : 2.0
    },
    "style" : "朱",
    "mark" : "・"
  } ],
  "gojunelements" : [ {
    "style" : "墨",
    "mark" : "レ"
  } ],
  "kanaelements" : [ {
    "targetLength" : 1,
    "position" : 0,
    "positionText" : "右",
    "style" : "墨",
    "text" : "ヨリ"
  } ]
}, {
  "place" : {
    "lineNumber" : 3,
    "columnNumber" : 9
  },
  "character" : "陑",
  "linename" : "巻4:1オ03",
  "warityu" : false,
  "warityu_kaigyo" : false,
  "elements" : [ {
    "position" : {
      "x" : -2.0,
      "y" : 2.0
    },
    "style" : "墨",
    "mark" : "∞"
  } ],
  "gojunelements" : [ ],
  "kanaelements" : [ {
    "targetLength" : 1,
    "position" : 0,
    "positionText" : "右",
    "style" : "墨",
    "text" : "シ"
  } ]
}] 
代码语言:javascript
复制
function toCSV(json) {
  var csv = "";
  var keys = (json[0] && Object.keys(json[0])) || [];
  csv += keys.join(',') + '\n';
  for (var line of json) {
    csv += keys.map(key => line[key]).join(',') + '\n';
  }
  return csv;
}

console.log(toCSV(json));
EN

回答 1

Stack Overflow用户

发布于 2022-04-14 16:59:42

这里有一篇博客文章,有人就是这么做的。

https://medium.com/@danny.pule/export-json-to-csv-file-using-javascript-a0b7bc5b00d2

这是他的密码的要点。

csv-js

如果博客和要点消失了(链接腐烂是真的),下面是他所做的事情:

代码语言:javascript
复制
function convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
    }

    return str;
}

function exportCSVFile(headers, items, fileTitle) {
    if (headers) {
        items.unshift(headers);
    }

    // Convert Object to JSON
    var jsonObject = JSON.stringify(items);

    var csv = this.convertToCSV(jsonObject);

    var exportedFilenmae = fileTitle + '.csv' || 'export.csv';

    var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", exportedFilenmae);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

var headers = {
    model: 'Phone Model'.replace(/,/g, ''), // remove commas to avoid errors
    chargers: "Chargers",
    cases: "Cases",
    earphones: "Earphones"
};

itemsNotFormatted = [
    {
        model: 'Samsung S7',
        chargers: '55',
        cases: '56',
        earphones: '57',
        scratched: '2'
    },
    {
        model: 'Pixel XL',
        chargers: '77',
        cases: '78',
        earphones: '79',
        scratched: '4'
    },
    {
        model: 'iPhone 7',
        chargers: '88',
        cases: '89',
        earphones: '90',
        scratched: '6'
    }
];

var itemsFormatted = [];

// format the data
itemsNotFormatted.forEach((item) => {
    itemsFormatted.push({
        model: item.model.replace(/,/g, ''), // remove commas to avoid errors,
        chargers: item.chargers,
        cases: item.cases,
        earphones: item.earphones
    });
});

var fileTitle = 'orders'; // or 'my-unique-title'

exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55788595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档