admin管理员组文章数量:1333442
I want to create a JSON object from the contents of a CSV file. The CSV file is loaded locally via the FileReader
API and that seems to work, however I am having trouble structuring the JSON in the desired way.
My code for loading the CSV file looks like this:
<!DOCTYPE html>
<html>
<body>
<p>Select local CSV File:</p>
<input id="csv" type="file">
<output id="out"> input file content</output>
<script>
var fileInput = document.getElementById("csv"),
readFile = function () {
var reader = new FileReader();
reader.onload = function () {
// Display CSV file contents
document.getElementById('out').innerHTML = reader.result;
};
reader.readAsBinaryString(fileInput.files[0]);
};
fileInput.addEventListener('change', readFile);
</script>
</body>>
</html>
The code above allows me to load the contents of the CSV file and display them on the current page. To structure the CSV data into the desired format above I tried the following, however it didn't work to me:
<!DOCTYPE html>
<html>
<body>
<script>
var fileReader = new FileReader();
function getFile(inputFile) {
let file = inputFile.files[0];
fileReader.readAsText(file);
}
function csvJSON(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 JSON.stringify(result); //JSON
}
function readFile(evt) {
let parsed = csvJSON(evt.target.result);
return parsed;
}
</script>
</body>
</html>
How can I acquire my expected JSON object(s)? Any suggestions would be appreciated
I want to create a JSON object from the contents of a CSV file. The CSV file is loaded locally via the FileReader
API and that seems to work, however I am having trouble structuring the JSON in the desired way.
My code for loading the CSV file looks like this:
<!DOCTYPE html>
<html>
<body>
<p>Select local CSV File:</p>
<input id="csv" type="file">
<output id="out"> input file content</output>
<script>
var fileInput = document.getElementById("csv"),
readFile = function () {
var reader = new FileReader();
reader.onload = function () {
// Display CSV file contents
document.getElementById('out').innerHTML = reader.result;
};
reader.readAsBinaryString(fileInput.files[0]);
};
fileInput.addEventListener('change', readFile);
</script>
</body>>
</html>
The code above allows me to load the contents of the CSV file and display them on the current page. To structure the CSV data into the desired format above I tried the following, however it didn't work to me:
<!DOCTYPE html>
<html>
<body>
<script>
var fileReader = new FileReader();
function getFile(inputFile) {
let file = inputFile.files[0];
fileReader.readAsText(file);
}
function csvJSON(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 JSON.stringify(result); //JSON
}
function readFile(evt) {
let parsed = csvJSON(evt.target.result);
return parsed;
}
</script>
</body>
</html>
How can I acquire my expected JSON object(s)? Any suggestions would be appreciated
Share edited Apr 30, 2019 at 22:47 beyond_inifinity asked Feb 25, 2019 at 18:50 beyond_inifinitybeyond_inifinity 45314 silver badges30 bronze badges 1-
Just curious but is this your actual CSV structure? It seems like there should be a newline
\n
character after every 6 entries... – War10ck Commented Feb 25, 2019 at 19:14
3 Answers
Reset to default 2One 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);
If you are struggling to parse data, you can also use PapaParse, it has a lot of configurations and it's pretty easy to use:
// Parse CSV string
var data = Papa.parse(csv);
See more information at https://www.papaparse./demo
var csv = '"Timestamp","Enter First Name:","Enter Middle Initial","Enter Last Name:","Enter UIN:","Are you attending the event?"\n"2019/02/22 12:41:56 PM CST","Jonathan","Samson","Rowe","123456789","No"\n"2019/02/22 12:44:56 PM CST","phil","Aspilla","beltran","123456788","Yes"';
var csvJSON = function(csv) {
let vals = csv.split('\n'), ret = [];
for( let i = 1, len = vals.length; i < len; i++ ){
let person = vals[i].split(',');
ret.push({
uin : person[4],
studentInfo : {
firstName : person[1],
middleName : person[2],
lastName : person[3],
rsvpStatus : person[5]
}
});
}
return JSON.stringify(ret);
}
console.log(csvJSON(csv));
This is assuming the structure of the CSV is always the same.
本文标签: htmlCreate structured JSON object from CSV file in JavaScriptStack Overflow
版权声明:本文标题:html - Create structured JSON object from CSV file in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742286650a2447049.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论