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

前端 未结 16 2139
一整个雨季
一整个雨季 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: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();
    }
    

提交回复
热议问题