angular js csv string to json array

时间:2017-01-18 14:15:44

标签: javascript json csv

我有一些以逗号分隔的数据;

"HotelName","Remained","Date"
"Maxx","4","Jun 26 2016"
"Voyage","3","Jun 24 2016"

我需要将它转换为如下所示的json数组。我怎样才能在我的javascript代码中执行此操作?

[
  {
    HotelName:"Maxx",
    Remained:"4",
    Date:"Jun 26 2016"
  },
  {
    HotelName:"Voyage",
    Remained:"3",
    Date:"Jun 24 2016"
  }
]

3 个答案:

答案 0 :(得分:0)

创建一个数组var data = new Array(),按照data.push({ item : value})推送数据,然后进行转换data_json = JSON.stringify(data)。我将它用于我的angularprojects。

答案 1 :(得分:0)

因为它是一个字符串,所以你可以拆分它。

var lines data.split('\n');
var array = [];
if(lines.length > 0){
    var titles = lines[0].split(',');
    for(var i=1; i<lines.length; ++i){
        var obj = lines[i].split(',');
        var newItem = {};
        //you should check that titles and obj are of same length
        for(var j=0, j<titles.length; ++j){
            newItem[titles[j]] = obj[j];
        }
        array.push(newItem);
    }
}

答案 2 :(得分:0)

我想来自远程服务器的响应是字符串化的JSON数据。

// Possible a CSV data string from your server;
var csvData = "\"HotelName\",\"Remained\",\"Date\"\"Maxx\",\"4\",\"Jun 26 2016\",\"Voyage\",\"3\",\"Jun 24 2016\"";

var NUMBER_OF_COLUMNS = 3;
var columns = [];
var arrayData = [];

// Remove double quotations in csvData and convert it to the array;
csvData = csvData.replace(/"/g, "").split(',');
columns = csvData.slice(0, NUMBER_OF_COLUMNS);
csvData = csvData.slice(NUMBER_OF_COLUMNS);

var rowObject = {};
csvData.forEach(function(item, index) {
  rowObject[columns[index % (NUMBER_OF_COLUMNS)]] = item;
  if (index % (NUMBER_OF_COLUMNS) == 2) {
    arrayData.push(rowObject);
    rowObject = {};
  }
})

console.log(arrayData);
/*
  [ 
    {
      DataMaxx: "Voyage",
      HotelName: "4",
      Remained: "Jun 26 2016"
    }
  ]
*/