Convert CSV Data into JSON Format Using JavaScript

Converting CSV to JSON using JavaScript

Your initial approach looks pretty good. We just need some more modifications to the data you generated. Instead of directly mapping each row to JSON, first keep data in the array as a line item, and then build the JSON data as follows.

var csv = `,Name,Class,Region_count,Coordinates
0,foto_1jpg.jpg,tennis,1,"""all_points_x"":[154,157,230,275,278,218,160,112,113,154],""all_points_y"":[461,461,455,495,576,625,625,563,505,463]"
1,foto_1jpg.jpg,soccer,2,"""all_points_x"":[446,557,685,795,826,815,738,628,505,422,346,331,354,443],""all_points_y"":[230,186,212,321,411,538,641,687,684,632,525,426,331,224]"
2,foto_1jpg.jpg,basket,3,"""all_points_x"":[941,1065,1161,1310,1438,1497,1509,1471,1382,1279,1124,998,916,874,847,874,938],""all_points_y"":[132,44,26,48,144,266,396,514,628,673,687,631,560,479,328,233,135]"
3,foto_2jpg.jpg,soccer,1,"all_points_x:[331,403,518,626,688,734,758,681,594,484,369,314,282,274,329],""all_points_y"":[399,340,316,342,380,463,607,736,787,796,745,683,592,503,405]"
4,foto_2jpg.jpg,basket,2,"""all_points_x"":[972,887,830,802,789,804,857,963,1050,1135,1220,1284,1314,1307,1263,1178,1116,1057,955],""all_points_y"":[144,195,261,327,397,484,579,639,660,647,603,524,424,335,238,174,146,140,157]"
5,foto_2jpg.jpg,tennis,3,"all_points_x:[1186,1233,1273,1282,1267,1231,1178,1154,1135,1131,1142,1182],""all_points_y"":[921,921,891,845,806,777,775,789,819,859,895,919]"
6,foto_3jpg.jpg,soccer,1,"""all_points_x"":[65,43,49,107,160,215,290,351,406,431,409,373,334,274,203,150,107,70],""all_points_y"":[349,421,503,586,622,630,629,593,537,465,356,313,283,264,256,278,303,346]"
7,foto_3jpg.jpg,basket,2,"""all_points_x"":[523,588,647,739,809,854,871,877,860,845,830,823,816,811,804,802,796,774,765,753,726,712,699,685,682,671,670,666,664,632,601,583,549,515,496,469,446,448,467,518],""all_points_y"":[242,203,196,206,247,307,361,436,491,509,515,521,530,537,549,561,572,583,583,562,550,547,554,557,571,578,591,601,620,615,612,608,588,552,532,496,428,370,319,244]"
8,foto_3jpg.jpg,tennis,3,"all_points_x:[838,881,901,917,912,888,869,845,821,804,792,791,813],""all_points_y"":[544,544,569,600,627,646,654,654,651,634,601,578,552]"`;

var items = []

var rows = csv.split(/\n/g);
var keys = rows.shift().split(",");

rows.forEach(raw_row => {
var row = {};
var columns = raw_row.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

columns.forEach((column, index)=>{
var key = keys[index];
if(!key) 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;

});
items.push(row);
});

const map = {}
for (const item of items) {
if (!map[item['Name']]) {
map[item['Name']] = {
'filename': item['Name'],
'regions': [],
'file_attributes': {}
}
}
map[item['Name']].regions.push(
{
"shape_attributes": item['Coordinates'],
"region_attributes": { "name": item['Class'] }
}
)
}

console.log(map)

How to convert csv file data to json object in reactjs?

You can use an external library like Papa Parse to parse the CSV data.

A simple input tag with type as file would work to read the CSV data.

      <input
type="file"
accept=".csv,.xlsx,.xls"
onChange={handleFileUpload}
/>

Please declare handleFileUpload function and use the library inside to parse the read data.

Here's an example which will read a CSV file and log the corresponding JSON:

import Papa from "papaparse";

export default function App() {
return (
<div className="App">
<input
type="file"
accept=".csv,.xlsx,.xls"
onChange={(e) => {
const files = e.target.files;
console.log(files);
if (files) {
console.log(files[0]);
Papa.parse(files[0], {
complete: function(results) {
console.log("Finished:", results.data);
}}
)
}
}}
/>
</div>
);
}

convert csv file to json object datatable

As far as I know, for most scenarios, you can turn csv into a js Array of Arrays, a Matrix, or any javascript object that follows your charting tool convention.

You may need to:

  1. Get the CSV file content
  2. Parse it
  3. Wrap the results from 2 into your charting tool json(?)
  4. Call your charting library

For 1, if the CSV file is hosted in your domain, you can do a simple XMLHttpRequest, else try searching here "same origin policy".

The tricky part is the point 2. I've seen several failed attempts for parsing CSV files by hand (semicolons can be contained as part of the value, etc)... Check out the link.

Create structured JSON object from CSV file in JavaScript?

One approach to this would be to iterate through your input CSV data on increments of "6" (where 6 represents the number of different bits of data for each student) to capture all student data per CSV row, and then populate an array of structured JSON objects in the desired format like so:

/* Helper function to perform the CSV to JSON transform */function convertToJson(inputCsv) {
/* Split input string by `,` and clean up each item */ const arrayCsv = inputCsv.split(',').map(s => s.replace(/"/gi, '').trim())
const outputJson = [];
/* Iterate through input csv at increments of 6, to capture entire CSV row per iteration */ for (let i = 6; i < arrayCsv.length; i += 6) {
/* Extract CSV data for current row, and assign to named variables */ const [date, firstName, middleName, lastName, uin, rsvpStatus] = arrayCsv.slice(i, i + 6) /* Populate structured JSON entry for this CSV row */ outputJson.push({ uin, studentInfo: { firstName, middleName, lastName, rsvpStatus } }); }
return outputJson;}
/* Input CSV data from your exsiting code */const csv = `"Timestamp", "Enter First Name:", "Enter Middle Initial", "Enter Last Name:", "Enter UIN:", "Are you attending the event?", "2019/02/22 12:41:56 PM CST", "Jonathan", "Samson", "Rowe", "123456789", "No", "2019/02/22 12:44:56 PM CST", "phil", "Aspilla", "beltran", "123456788", "Yes"`
const json = convertToJson(csv);
console.log(json);

Converting from CSV string to Json in javascript

Looks like your problem is the attribute names from your current solution. They sometimes have "," in the end.

If that is the case, the simplest solution is just to remove them using the replace method.

console.log( "something,".replace( ",", "" ) )
console.log( "age".replace( ",", "" ) )

Read CSV over SSH and convert to JSON

The null bytes \x00 are pointing towards an encoding/decoding issue. The CSV file might be encoded using UTF-16, but Buffer.toString() by default decodes the data using UTF-8. You can change that to data.toString('utf16le') (or data.toString('ucs2')) to force using the correct encoding.



Related Topics



Leave a reply



Submit