简体   繁体   中英

Convert Json file to CSV with Javascript

I have a problem with my project, i must convert a json file to csv using javascript, but i don't know how to do it.

Can you help me please?

I've tried this code found on this site but it doesn't work for me because it displaying me this but it displaying me that:

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] :

EDIT: This is what i want for the structure of the csv: lineNumber, columnNumber, character, linename, warityu, warityu_kaigyo, x, y, style, mark, style, mark, targetLenght, position, positionText, style, text,

This is the code:

  "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" : "シ"
  } ]
}] 
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));

Here is a blog post where someone did just that.

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

Here is the gist with his code.

https://gist.github.com/dannypule/48418b4cd8223104c6c92e3016fc0f61#file-json_to_csv-js

And in case the blog and the gist goes away (link rot is real) here is what he did:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM