如何读取csv文件并将其转换为javascript中的对象

时间:2016-05-06 07:41:41

标签: javascript json csv

您好我正在通过filereader api从本地读取文件。在阅读文件后我将它们转换为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
  },

我尝试了很多解析器,但是输出与下面的输出不同。有人帮助我如何实现以下输出

1 个答案:

答案 0 :(得分:0)

查看这个小提琴:

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

希望它可以完成这项工作,甚至可以更好地了解如何实现自己的脚本!

在小提琴中查看以下功能,它会指向正确的方向

$("h2 input").attr({maxlength: 30});