使用Angular.js将上传的csv文件对象转换为json对象

时间:2017-03-08 10:19:09

标签: javascript angularjs

我已经尝试了与此转换相关的建议。我已将文件读入文件对象,现在我必须使用angularjs将文件对象转换为json对象数组。 读取文件对象如下:

id,category,type,name,value,isEnabled,key
1,kk,t,dsa,3,FALSE,A
2,jj,h,gdfjkl,5,FALSE,A
3,jj,u,hdg,9,FALSE,A
4,jj,p,rwe,7,FALSE,A

respones变量包含读取文件.Below是控制器文件:

(function () {
'use strict';
var myApp = angular.module('app');
myApp.controller('FileUploadController', function ($scope, fileUploadService) {

    $scope.uploadFile = function () {
        var file = $scope.myFile;
        console.log("file::"+file);
        var fileVal=[{}];
       /* var uploadUrl = "../server/service.php", //Url of webservice/api/server*/
        var uploadUrl = "../server/Book1.csv",
            promise = fileUploadService.uploadFileToUrl(file, uploadUrl);
 console.log("promise"+promise);

        promise.then(function (response) {
            $scope.serverResponse = response;
 console.log("serverResponse::"+response);
 var splitvar=",";
 var splitnewline="\n";
 for(var i=0;i<(response!=null);i++){
if(response[i]==splitvar){
    fileVal[i]=response[i];
}
else if(response[i]==splitnewline){     
}        
     console.log(fileVal[i]);   
 };
 console.log("length:"+response.length);
        }, function () {
            $scope.serverResponse = 'An error has occurred';
        })
    };
});
 })();

以下是我的html文件:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>File Upload Demo</title>
<script src="../scripts/angular.min.js"></script>
<script type="text/javascript" src="app.module.js"></script>
<script type="text/javascript" src="controllers.js"></script>
<script type="text/javascript" src="directives.js"></script>
<script type="text/javascript" src="services.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body ng-controller="FileUploadController">
<h2>File Upload Demo</h2>

<div class="panel panel-default">
    <div class="panel-body">
        <form>
            <div class="form-group">
                <label for="myFileField">Select a file: </label>
                <input type="file" demo-file-model="myFile"  class="form-control" id ="myFileField"/>
            </div>
            <button ng-click="uploadFile()" class = "btn btn-primary">Upload File</button>
        </form>
    </div>
</div>
<div>{{serverResponse}}</div>
</body>
</html>

现在我无法将其转换为json对象。

预期输出样本:

[{"id":1,"category":"kk","type":"t","name":"dsa","value":3,"isEnabled":"FALSE","key":"A"},
{"id":2,"category":"jj","type":"h","name":"gdfjkl","value":5,"isEnabled":"FALSE","key":"A"},
{"id":3,"category":"jj","type":"u","name":"hdg","value":9,"isEnabled":"FALSE","key":"A"},
{"id":4,"category":"jj","type":"p","name":"rwe","value":7,"isEnabled":"FALSE","key":"A"}]

有关同样的想法。

2 个答案:

答案 0 :(得分:0)

有一些很好的指令可用于此类任务。您不必再重复执行所有操作。

我强烈推荐angular-csv-import,此处为demo

答案 1 :(得分:0)

如果你想将cvs实现为json,那么找到下面的演示示例

https://jsfiddle.net/mohan_rathour/Lt3wjgfx/7/

&#13;
&#13;
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.

function CSVToArray(strData, strDelimiter) {
    strDelimiter = (strDelimiter || ",");
    var objPattern = new RegExp((
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
    var arrData = [[]];
    var arrMatches = null;
    while (arrMatches = objPattern.exec(strData)) {
        var strMatchedDelimiter = arrMatches[1];
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
           arrData.push([]);
        }
        if (arrMatches[2]) {
           var strMatchedValue = arrMatches[2].replace(
            new RegExp("\"\"", "g"), "\"");
        } else {
            var strMatchedValue = arrMatches[3];
        }
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    return (arrData);
}

function CSV2JSON(csv) {
    var array = CSVToArray(csv);
    var objArray = [];
    for (var i = 1; i < array.length; i++) {
        objArray[i - 1] = {};
        for (var k = 0; k < array[0].length && k < array[i].length; k++) {
            var key = array[0][k];
            objArray[i - 1][key] = array[i][k]
        }
    }

    var json = JSON.stringify(objArray);
    var str = json.replace(/},/g, "},\r\n");

    return str;
}

$("#convert").click(function() {
    var csv = $("#csv").val();
    var json = CSV2JSON(csv);
    $("#json").val(json);
});
&#13;
#heading { font-size: x-large; font-weight: bold; }
.text { width: 99%; height: 200px; }
.small { font-size: small; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="heading">CSV to JSON Converter</p>
    <p class="small"><a href="https://jsfiddle.net/mohan_rathour/Lt3wjgfx/5/" target="_blank">JSON to CSV Converter</a>
    <hr />
    <p>Paste Your CSV Here:</p>
    <textarea id="csv" class="text">"Id","UserName"
"1","Mohan"
"2","Sohan"
"1","Abhi"</textarea>
    <br />
    <button id="convert">Convert to JSON</button>
     &nbsp;&nbsp;
    <textarea id="json" class="text"></textarea>
&#13;
&#13;
&#13;