convert json to csv format

前端 未结 2 1231
花落未央
花落未央 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/

    0 讨论(0)
  • 2020-12-21 22:13

    I posted a couple of links in the comments as I was researching your answer, but now I am pretty convinced this is the way to do it.

    Install the node package, and then use the following with your own json string, (which I just lifted from the link above.):

    var converter = require('json-2-csv');
    
    var documents = [
        {
            Make: 'Nissan',
            Model: 'Murano',
            Year: '2013',
            Specifications: {
                Mileage: '7106',
                Trim: 'S AWD'
            }
        },
        {
            Make: 'BMW',
            Model: 'X5',
            Year: '2014',
            Specifications: {
                Mileage: '3287',
                Trim: 'M'
            }
        }
    ];
    
    var json2csvCallback = function (err, csv) {
        if (err) throw err;
        console.log(csv);
    };
    
    converter.json2csv(documents, json2csvCallback);
    

    This will return:

    Make,Model,Year,Specifications.Mileage,Specifications.Trim
    Nissan,Murano,2013,7106,S AWD
    BMW,X5,2014,3287,M
    
    0 讨论(0)
提交回复
热议问题