2016-05-06 83 views
-1

嗨,我正在通過filereader api從本地讀取文件。閱讀文件後,我將它們轉換成javascript對象。如何讀取csv文件並將其轉換爲javascript中的對象

<!DOCTYPE html> 
<html> 
<head> 
    <title> JSon Parsing </title> 
    <link rel="stylesheet" href="main.css" 
</head> 
<body> 

    <input type="file" id="fileInput" name="fileInput" onchange="readFile()"> 


    <script type="text/javascript"> 
     function readFile(){ 
     var file = document.getElementById("fileInput").files[0]; 
     var reader = new FileReader(); 
     reader.onload = function(evt){ 
      var resultText = evt.target.result; 
      console.log(resultText); 
     } 
     var newFile = file.slice(0,5000); 
     reader.readAsText(newFile);    
     } 
    </script> 
</body> 
</html> 

的輸出中應該像下面

{ 
    "policyID": 119736, 
    "statecode": "FL", 
    "county": "CLAY COUNTY", 
    "eq_site_limit": 498960, 
    "hu_site_limit": 498960, 
    "fl_site_limit": 498960, 
    "fr_site_limit": 498960, 
    "tiv_2011": 498960, 
    "tiv_2012": 792148.9, 
    "eq_site_deductible": 0, 
    "hu_site_deductible": 9979.2, 
    "fl_site_deductible": 0, 
    "fr_site_deductible": 0, 
    "point_latitude": 30.102261, 
    "point_longitude": -81.711777, 
    "line": "Residential", 
    "construction": "Masonry", 
    "point_granularity": 1 
    }, 
    { 
    "policyID": 448094, 
    "statecode": "FL", 
    "county": "CLAY COUNTY", 
    "eq_site_limit": 1322376.3, 
    "hu_site_limit": 1322376.3, 
    "fl_site_limit": 1322376.3, 
    "fr_site_limit": 1322376.3, 
    "tiv_2011": 1322376.3, 
    "tiv_2012": 1438163.57, 
    "eq_site_deductible": 0, 
    "hu_site_deductible": 0, 
    "fl_site_deductible": 0, 
    "fr_site_deductible": 0, 
    "point_latitude": 30.063936, 
    "point_longitude": -81.707664, 
    "line": "Residential", 
    "construction": "Masonry", 
    "point_granularity": 3 
    }, 

我已經嘗試了許多解析器,但輸出中是不同的從下面的ouput.plz有人幫助我如何能實現下面的輸出中

+0

如果您在使用第三方庫很舒服,我推薦使用http://papaparse.com / – Sajal

回答

0

結帳這小提琴:

https://jsfiddle.net/barney/7vpAJ/

希望它能夠完成這項工作,甚至更好地給你一個關於如何實現你自己的腳本的想法!

結帳的小提琴下面的函數,它會爲你指明正確的方向

function csvToArray(csvString){

相關問題