处理JQuery-CSV对象并将其格式化为txt文件

问题描述

我有一个传入的txt / csv文件,其中包含很多信息(58列),基本上,我将需要处理一些信息(仅是姓名和电话号码)。因此,我必须能够获取全部信息,从中获取所需信息,然后对其进行格式化。

  • 要获取全部信息,我使用了terales answer,该文件可以上传。
  • 要处理我正在使用此库JQuery-CSV的信息,此操作将读取文件内容并将其转换为JSON对象,目前为止,我很棘手。我有对象,但无法按需访问它,因此无法格式化它以编写新的txt文件。我可能在文档中丢失了某些内容,这应该很简单。这是我的代码示例:

HTML

<link href="https://fonts.googleapis.com/css?family=Lato|Roboto|Source+Code+Pro" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/monokai.min.css">
<link rel="stylesheet" href="demo.css">

<div class="row" style="margin-bottom:8px;position:relative;">
    <h2>Contacts</h2>
    <div class="col-md-12">
        <label for="input-file">Select your file:</label><br>
        <input type="file" id="input-file">
        <input id="run" type="button" value="Format" />
    </div>
</div>


<textarea id="content-target"></textarea>
<textarea id="result"></textarea>

<script src="http://code.jquery.com/jquery-3.3.1.slim.js" integrity="sha256-fNXJFIlca05BIO2Y5zh1xrShK3ME+/lYZ0j+ChxX2DA=" crossorigin="anonymous"></script>
<script src="http://typeiii.github.io/jquery-csv/src/jquery.csv.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
<script src="jquery-csv.js"></script>

JS

<script>

    $("#content-target").hide();
    $("#result").hide();
    $("#run").hide();
    document.getElementById('input-file').addEventListener('change',getFile)

    function getFile(event) {
        const input = event.target
        if ('files' in input && input.files.length > 0) {
            placeFileContent(
                document.getElementById('content-target'),input.files[0])
            $("#run").show();
        }
    }

    function placeFileContent(target,file) {
        readFileContent(file).then(content => {
            target.value = content
        }).catch(error => console.log(error))
    }

    function readFileContent(file) {
        const reader = new FileReader()
        return new Promise((resolve,reject) => {
            reader.onload = event => resolve(event.target.result)
            reader.onerror = error => reject(error)
            reader.readAsText(file)
        })
    }

    // enable syntax highlighting
      hljs.initHighlightingOnLoad();

      $(document).ready(() => {
        parse();
      });

      $('#run').bind('click',function () {
          parse();
          //format();
      });

      function parse() {
        const input = $('#content-target').val();
        const data = $.csv.toObjects(input);
        $('#result').empty();
        //$('#result').html(JSON.stringify(data,null,2));
        $("#result").show();
    };    

</script>

format()函数将在对象内访问特定的索引(我在上面提到的名称和电话号码),并执行正则表达式操作以对其进行格式化。但是正如我所说,我无法访问这些索引,在我的特定情况下,我认为语法 data [0] .Name 或类似 data [index] .ColumnName 一般而言应该没问题。

这是我收到的数据的一小部分样本:

Name;Given Name;Additional Name;Family Name;Yomi Name;Given Name Yomi;Additional Name Yomi;Family Name Yomi;Name Prefix;Name Suffix;Initials;Nickname;Short Name;Maiden Name;Birthday;Gender;Location;Billing Information;Directory Server;Mileage;Occupation;Hobby;Sensitivity;Priority;Subject;Notes;Language;Photo;Group Membership;E-mail 1 - Type;E-mail 1 - Value;E-mail 2 - Type;E-mail 2 - Value;Phone 1 - Type;Phone 1 - Value;Phone 2 - Type;Phone 2 - Value;Phone 3 - Type;Phone 3 - Value;Address 1 - Type;Address 1 - Formatted;Address 1 - Street;Address 1 - City;Address 1 - PO Box;Address 1 - Region;Address 1 - Postal Code;Address 1 - Country;Address 1 - Extended Address;Organization 1 - Type;Organization 1 - Name;Organization 1 - Yomi Name;Organization 1 - Title;Organization 1 - Department;Organization 1 - Symbol;Organization 1 - Location;Organization 1 - Job Description;Website 1 - Type;Website 1 - Value
A1 Soluções;A1;;Soluções;;;;;;;;;;;;;;;;;;;;;;;;;* myContacts;;;;;Disp. móvel;8006009510;;;;;;;;;;;;;;;;;;;;;;;
Adelson;Adelson;;;;Adelson;;;;;;;;;;;;;;;;;;;;;;;* myContacts;;;;;Disp. móvel;027 99978-1045;;;;;;;;;;;;;;;Aluguel da Casa;;;;;;;;
Admilson;Admilson;;;;;;;;;;;;;;;;;;;;;;;;;;;* myContacts;;;;;Mobile;033 98888-1078;;;;;;;;;;;;;;;Paroquia Sagrado Coração de Jesus;;Bingo;;;;;;

解决方法

异步调用存在一些问题。我修复了您的代码,因为只有当异步函数结束时(即:fileReader.onload),您才能继续:

$("#content-target").hide();
$("#result").hide();
$("#run").hide();
document.getElementById('input-file').addEventListener('change',getFile)

function getFile(event) {
  const input = event.target
  if ('files' in input && input.files.length > 0) {
      var fileReader = new FileReader();
      fileReader.onload = function(fileLoadedEvent) {
          //
          //  only after you read the file you can go on with the data...
          //
          var textFromFileLoaded = fileLoadedEvent.target.result;
          $("#content-target").text(textFromFileLoaded).show();
          $("#run").show();
          parse();
      }
      fileReader.readAsText(input.files[0],"UTF-8");
  }
}




 function parse() {
    const input = $('#content-target').text();
    const data = $.csv.toObjects(input,{"separator": ";"});
    $('#result tbody').empty();
    data.forEach(function (e) {
        // get arguments
        var name = e.Name;
        var phoneType = e['Phone 1 - Type'];
        var phoneValue = e['Phone 1 - Value'];

        // create a row and append to the table
        $('#result tbody').append($('<tr><td>' + name + '</td><td>' + phoneType + ' </td><td>' + phoneValue + '</td></tr>'));

    });
    $("#result").show();
};
table,th,td {
    border: 1px solid black;
    border-collapse: collapse;
    width: 33%;
}
table {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://typeiii.github.io/jquery-csv/src/jquery.csv.js"></script>
<link href="https://fonts.googleapis.com/css?family=Lato|Roboto|Source+Code+Pro" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/monokai.min.css">


<div class="row" style="margin-bottom:8px;position:relative;">
    <h2>Contacts</h2>

    <div class="col-md-12">
        <label for="input-file">Select your file:</label><br>
        <input type="file" id="input-file">
        <input id="run" type="button" value="Format"/>
    </div>
</div>
<textarea id="content-target"></textarea>
<table id="result">
    <thead>
    <tr>
        <th>name</th>
        <th>Phone Type</th>
        <th>Phone Value</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...