0

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));
MomoMotus
  • 1
  • 2
  • 4
    you're trying to convert a complex object graph into CSV but you're not specifying what the expected CSV output would look like. The fact that you're trying to serialize an array of objects that contains arrays suggests a mapping to a "flat" structure like CSV isn't even possible – jamey graham Apr 22 '19 at 03:10
  • Thank you for your answer, but the fact is that i never work on this type of file and i don't know what i must do. After that, i have to put the csv into a data base, maybe the best structure is : lineNumber, columnNumber, character, linename, warityu, warityu_kaigyo, x, y, style, mark, style, mark, targetLenght, position, positionText, style, text, ? Are tou sure this is impossible to convert into csv? Thank you again for your help – MomoMotus Apr 22 '19 at 04:46
  • @MomoMotus, since it is a complex type with variable-sized-array inside each JSON object. It is impossible or really bad to fit entire JSON data in one relational table. Instead, you need to apply normalization and create multiple CSV files with lookup and main tables. – Ashokan Sivapragasam Apr 22 '19 at 05:32
  • this isn't a question about file format - it's all about the structure of the data. the fact that elements, kanaelements, and gojunelements are arrays means that you have a "0 to many" parent-child relationship, something which cannot be represented in a flat format like CSV or a single row in a database. suggest to read up some on [object relational mapping](https://stackoverflow.com/q/1279613/3456359) – jamey graham Apr 22 '19 at 12:52

1 Answers1

0

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
Joshua Dance
  • 8,847
  • 4
  • 67
  • 72