0

I have some comma-separated data;

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

I need to convert this to a json array like below. How can I do that in my javascript code?

[
  {
    HotelName:"Maxx",
    Remained:"4",
    Date:"Jun 26 2016"
  },
  {
    HotelName:"Voyage",
    Remained:"3",
    Date:"Jun 24 2016"
  }
]
8
  • What have you tried so far? Have you researched your question before asking? Commented Jan 18, 2017 at 14:16
  • up to now, I've tried different combinations of angularjs methods like angular.fromJson, JSON.parse, JSON.stringify etc. Commented Jan 18, 2017 at 14:20
  • techslides.com/convert-csv-to-json-in-javascript took me two seconds to google. Commented Jan 18, 2017 at 14:25
  • impressed by your googling skills good for you, I have seen this, it adds extra quote marks and mismatches label-value pairs, since my data is with quotes, not in csv format Commented Jan 18, 2017 at 14:41
  • What is you data format ? (String ?) Commented Jan 18, 2017 at 14:45

3 Answers 3

0

Ceeate an array var data = new Array(), push data in it like so data.push({ item : value}) and then convert like so data_json = JSON.stringify(data). I use that for my angularprojects.

Sign up to request clarification or add additional context in comments.

Comments

0

Since it is a String, maybe you could split it.

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);
    }
}

Comments

0

I guess the response which comes from the remote server is a stringified JSON data.

// 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"
    }
  ]
*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.