convert json to csv format

前端 未结 2 1241
花落未央
花落未央 2020-12-21 21:31

I try to use as input a file in json format. Here is a snippet of example data.

[
{
id: 1671349531,
name: \"A Wild Restaurant Expansion\",
blurb: \"We are lo         


        
2条回答
  •  無奈伤痛
    2020-12-21 22:11

    Another implementation without json-2-csv that can handle complex data:

        // Some complex demo data
        var data = [
            {
                "id": "111",
                "name": "Johny Smith",
                "age": "23",
                "dates": [
                    {
                        "birthday": "01.01.1990",
                        "nameday": "02.02",
                        "phone": {
                            "home": "02123123123123",
                            "mobile": "07124123123",
                        }
                    }
                ]
            },
            {
                "id": "222",
                "name": "Jane Alex",
                "age": "43",
                "dates": [
                    {
                        "birthday": "06.06.1997",
                        "nameday": "03.03",
                        "phone": {
                            "home": "029999999999999",
                            "mobile": "0788888888",
                        }
                    }
                ]
            }
        ];
    
        // Converted string ready to be downloaded as csv
        var converted = toCsv(data);
    
        // This is used to automatically generate and download the  .CSV file
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(converted));
        element.setAttribute('download', "Output.csv");
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    
    
        //////////////////////////////////// THE MAGIC  -> ////////////////////////////////////
    
        function toCsv(arr) {
            arr = pivot(arr);
            return arr.map(function (row) {
                return row.map(function (val) {
                    return isNaN(val) ? JSON.stringify(val) : +val;
                }).join(',');
            }).join('\n');
        }
    
        function toConsumableArray(arr) {
            if (Array.isArray(arr)) {
                for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
                    arr2[i] = arr[i];
                }
                return arr2;
            } else {
                return Array.from(arr);
            }
        }
    
        function pivot(arr) {
            var mp = new Map();
    
            function setValue(a, path, val) {
                if (Object(val) !== val) {
                    // primitive value
                    var pathStr = path.join('.');
                    var i = (mp.has(pathStr) ? mp : mp.set(pathStr, mp.size)).get(pathStr);
                    a[i] = val;
                } else {
                    for (var key in val) {
                        setValue(a, key == '0' ? path : path.concat(key), val[key]);
                    }
                }
                return a;
            }
    
            var result = arr.map(function (obj) {
                return setValue([], [], obj);
            });
            let outcome = ([[].concat(toConsumableArray(mp.keys()))].concat(toConsumableArray(result)));
    
            return outcome;
        }
    

    See JS Fiddle -> https://jsfiddle.net/gbktnd1j/

提交回复
热议问题