0

I want to add an external CSV file into a JOSN Array in my JS Code.

I tried lots of codes, with no luck like this:

var map = {};
var rows = csv.split(/\n/g);
var keys = rows.shift().split(",");
rows.forEach(raw_row => {
  var row = {};
  var row_key;
  var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
  columns.forEach((column, index) => {
    var key = keys[index];
    if (!key) return;
    if (key === 'Name') {
      row_key = column;
      return;
    }
    if (key === "Coordinates") {
      column = column.replace(/""/g, '"');
      column = column.substring(1, column.length - 1);
      column = column.replace(/([a-zA-Z_]+):/g, `"$1":`);
      try {
        column = JSON.parse(`{${column}}`);
      } catch (e) {}
    }

    row[key] = column;
  });
  map[row_key] = row;
});
console.log(map);

but I believe my expectation is something else, so I dont get what I want. could some one pleae help me to change this csv(file):

contry;fromNr;toNr;Type;cust_1;cust_2
US;0;100;wood;max;nuk
DE;100;500;metal;max;pal

into JSON Array:

[{
  "country": "US",
  "fromNr": 0,
  "toNr": 100,
  "Type": "wood",
  "cust_1": "max",
  "cust_2": "nuk"
}, {
  "country": "DE",
  "fromNr": 100,
  "toNr": 500,
  "Type": "metal",
  "cust_1": "max"
}]
8
  • 1
    Why are you using rows.shift().split(",")? Your column names and values are delimited by ";". It should be rows.shift().split(";"). Commented Jul 13, 2021 at 14:32
  • its just one of the codes which I tried. could you create one please? Commented Jul 13, 2021 at 14:33
  • 1
    Don't re-invent the wheel, there are existing solutions for this, here Commented Jul 13, 2021 at 14:38
  • 1
    Maybe not what you want -but I saved myself a lot of headaches by using a CSV parsing library: Papa Parse. It also converts to JSON. Commented Jul 13, 2021 at 14:38
  • @Kokodoko I tried it, but the result come something wich I cant use it. I'll try it again. tnx anyway Commented Jul 13, 2021 at 14:40

3 Answers 3

2

You can use the below function csvIntoJson to convert.

    const csv = 'contry;fromNr;toNr;Type;cust_1;cust_2\nUS;0;100;wood;max;nuk\nDE;100;500;metal;max;pal';

const csvIntoJson = (csv, separator) => {
  let [headers, ...rows] = csv.split('\n');
  headers = headers.split(separator);
  rows = rows.map(row => row.split(separator));

  return rows.reduce((jsonArray, row) => {
    const item = row.reduce((item, value, index) => {
      return {...item, [headers[index]]: value};
    }, {});
    return jsonArray.concat(item);
  }, []);
};

const jsonArray = csvIntoJson(csv, ';');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but how can I use my external csv file which is already on my Server? how can i use it? because I want it to be changed automatically.
1

My suggestion use a library, But you still want to understand how it can be done then here is the simple code.

I have used ',' delimiter, You can change it to ';' or anything else as per your usecase.

steps:

  1. Read csv as text
  2. split text by new line to get rows
  3. split row by delimiter like ',' or ';'
  4. Do your stuff

code:

 function Upload(input){
        console.log("uploading");
        let file = input.files[0];

        let reader = new FileReader();

        reader.readAsText(file);

        
        reader.onload = function() {
            map_object = [];
            console.log(reader.result);
            var textByLine = (reader.result).split("\n")
            console.log(textByLine);

            // read header
            header = (textByLine[0]).split(',');
            // read data
            for(var i = 1 ; i< textByLine.length -1; i++){
                temp_row = {}
                row_data = textByLine[i].split(',');
                for (var j = 0 ; j< header.length; j++){
                    temp_row[header[j]] = row_data[j]
                } 
                console.log(temp_row);

                map_object.push(temp_row);
            }
            console.log(map_object);
            document.write(JSON.stringify(map_object));
            
        };

        reader.onerror = function() {
            console.log(reader.error);
        };
    }
<input type="file" id="fileUpload" accept='.csv' onchange="Upload(this)"/>

3 Comments

Thank you, but how can I use my external csv file which is already on my Server? how can i use it? because I want it to be changed automatically.
You didn't mention in the question that the file is on server. In that case I am assuming you are using node js!! Then just use a csv parser to read the file from the required path. Such as fast csv or node csv
Thank you for the hint. shold i install it? where? on my local pc or there is a link to add to my code like JQuery?
0

var data = "contry;fromNr;toNr;Type;cust_1;cust_2\nUS;0;100;wood;max;nuk\nDE;100;500;metal;max;pal";

function CSVtoJSON(csv) {
    var lines = csv.split("\n");
    var result = [];

    var headers = lines[0].split(";");
    for (var i = 1; i < lines.length; i++) {
        var obj = {};
        var currentline = lines[i].split(";");
        for (var j = 0; j < headers.length; j++) {
            obj[headers[j]] = currentline[j];
        }
        result.push(obj);

    }
    return result; 
}

console.log(CSVtoJSON(data));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.