How to convert JSON to CSV format and store in a variable

前端 未结 16 2116
一整个雨季
一整个雨季 2020-11-22 17:31

I have a link that opens up JSON data in the browser, but unfortunately I have no clue how to read it. Is there a way to convert this data using JavaScript in CSV format and

相关标签:
16条回答
  • 2020-11-22 17:46

    Sometimes objects have different lengths. So I ran into the same problem as Kyle Pennell. But instead of sorting the array we simply traverse over it and pick the longest. Time complexity is reduced to O(n), compared to O(n log(n)) when sorting first.

    I started with the code from Christian Landgren's updated ES6 (2016) version.

    json2csv(json) {
        // you can skip this step if your input is a proper array anyways:
        const simpleArray = JSON.parse(json)
        // in array look for the object with most keys to use as header
        const header = simpleArray.map((x) => Object.keys(x))
          .reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []);
    
        // specify how you want to handle null values here
        const replacer = (key, value) => (
          value === undefined || value === null ? '' : value);
        let csv = simpleArray.map((row) => header.map(
          (fieldName) => JSON.stringify(row[fieldName], replacer)).join(','));
        csv = [header.join(','), ...csv];
        return csv.join('\r\n');
    }
    
    0 讨论(0)
  • 2020-11-22 17:48
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>JSON to CSV</title>
        <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
    </head>
    <body>
        <h1>This page does nothing....</h1>
    
        <script type="text/javascript">
            var json3 = {
              "count": 2,
              "items": [{
                  "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
                  "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
                  "link": "http://wik.io/info/US/309201303",
                  "timestamp": 1326439500,
                  "image": null,
                  "embed": null,
                  "language": null,
                  "user": null,
                  "user_image": null,
                  "user_link": null,
                  "user_id": null,
                  "geo": null,
                  "source": "wikio",
                  "favicon": "http://wikio.com/favicon.ico",
                  "type": "blogs",
                  "domain": "wik.io",
                  "id": "2388575404943858468"
                },
                {
                  "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
                  "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
                  "link": "http://wik.io/info/US/309198933",
                  "timestamp": 1326439320,
                  "image": null,
                  "embed": null,
                  "language": null,
                  "user": null,
                  "user_image": null,
                  "user_link": null,
                  "user_id": null,
                  "geo": null,
                  "source": "wikio",
                  "favicon": "http://wikio.com/favicon.ico",
                  "type": "blogs",
                  "domain": "wik.io",
                  "id": "16209851193593872066"
                }
              ]
            };
    
            const items = json3.items
            const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
            const header = Object.keys(items[0])
            let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
            csv.unshift(header.join(','))
            csv = csv.join('\r\n')
    
            var link = document.createElement("a");    
            link.id="lnkDwnldLnk";
            document.body.appendChild(link);
            blob = new Blob([csv], { type: 'text/csv' }); 
            var csvUrl = window.webkitURL.createObjectURL(blob);
            var filename = 'UserExport.csv';
            jQuery("#lnkDwnldLnk")
            .attr({
                'download': filename,
                'href': csvUrl
            });
            jQuery('#lnkDwnldLnk')[0].click();
            document.body.removeChild(link);
        </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 17:52

    Try these Examples

    Example 1:

    JsonArray = [{
        "AccountNumber": "123",
        "AccountName": "abc",
        "port": "All",
        "source": "sg-a78c04f8"
    
    }, {
        "Account Number": "123",
        "Account Name": "abc",
        "port": 22,
        "source": "0.0.0.0/0",
    }]
    
    JsonFields = ["Account Number","Account Name","port","source"]
    
    function JsonToCSV(){
        var csvStr = JsonFields.join(",") + "\n";
    
        JsonArray.forEach(element => {
            AccountNumber = element.AccountNumber;
            AccountName   = element.AccountName;
            port          = element.port
            source        = element.source
    
            csvStr += AccountNumber + ',' + AccountName + ','  + port + ',' + source + "\n";
            })
            return csvStr;
    }
    

    Example2 :

    JsonArray = [{
        "AccountNumber": "1234",
        "AccountName": "abc",
        "inbound": [{
            "port": "All",
            "source": "sg-a78c04f8"
        },
        {
            "port": 22,
            "source": "0.0.0.0/0",
        }]
    }]
    
    JsonFields = ["Account Number", "Account Name", "port", "source"]
    
    function JsonToCSV() {
        var csvStr = JsonFields.join(",") + "\n";
    
        JsonArray.forEach(element => {
            AccountNumber = element.AccountNumber;
            AccountName = element.AccountName;
            
            element.inbound.forEach(inboundELe => {
                port = inboundELe.port
                source = inboundELe.source
                csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
            })
        })
        return csvStr;
    }
    

    You can even download the csv file using the following code :

    function downloadCSV(csvStr) {
    
        var hiddenElement = document.createElement('a');
        hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
        hiddenElement.target = '_blank';
        hiddenElement.download = 'output.csv';
        hiddenElement.click();
    }
    
    0 讨论(0)
  • 2020-11-22 17:59

    There are multiple options available to reuse the existing powerful libraries that are standards based.

    If you happen to use D3 in your project, then you can simply invoke:

        d3.csv.format or d3.csv.formatRows functions to convert an array of objects into csv string.

        d3.csv.formatRows gives you greater control over which properties are converted to csv.

        Please refer to d3.csv.format and d3.csv.formatRows wiki pages.

    There are other libraries available too like jquery-csv, PapaParse. Papa Parse has no dependencies - not even jQuery.

    For jquery based plugins, please check this.

    0 讨论(0)
提交回复
热议问题