gpt4 book ai didi

javascript - 如何净化在 javascript 中创建的结构化 json 文件的输出?

转载 作者:行者123 更新时间:2023-11-30 19:45:25 25 4
gpt4 key购买 nike

我学习了如何从 google 表单生成的 csv 文件创建结构化的 json 文件。但是,生成的 json 对象包含时间 header ,因为 google form 生成它并在从中创建 json 对象之前将其保存到 csv。

这是我试图解决的问题:

let inputCsv = `"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","670168228","No"
"2019/02/22 12:44:56 PM CST","Phil","Aspilla","beltran","6689144343","Yes"`

function convertToJson(inputCsv) {
//inputCsv passed from readfile function
/* Split input string by `,` and clean up each item */

var lines = inputCsv.split('\n');
lines.splice(0,1);

var arrayCsv = [];
for (var line = 0; line < lines.length; line++){
const lineArray = lines[line].split(',').map(s => s.replace(/"/gi, '').trim());
lineArray.splice(0,1);

arrayCsv[line] = lineArray;
}


const outputJson = [];

console.log(arrayCsv);
}

convertToJson(inputCsv)

基本上,当我从中创建结构化 json 对象时,我想摆脱输入 csv 文件的每一行的额外时间 header (如 `2019/02/22 12:41:56 CST),所以这是我想要的输出:

更新:所需的输出 json 文件

[{
"uin": "123456789",
"studentInfo": {
"firstName": "Jonathan",
"middleName": "Samson",
"lastName": "Rowe",
"rsvpStatus": "Yes"
}
},
{
"uin": "123456788",
"studentInfo": {
"firstName": "phil",
"middleName": "Aspilla",
"lastName": "beltran",
"rsvpStatus": "No"
}
}]

我不确定正则表达式在 javascript 中是如何工作的,我想从来自谷歌表单的 csv 中生成干净的结构化 json 对象。我怎样才能做到这一点?有什么办法吗?谢谢

最佳答案

您需要以所需格式构建对象,而不是插入数组。

let inputCsv = `"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","Christ","A","coda","670168228","No"
"2019/02/22 12:44:56 PM CST","jack","NA","Harvey","6689144343","Yes"`

function convertToJson(inputCsv) {
const keyMapping = {
"\"Enter First Name:\"" : 'firstName',
"\"Enter Middle Initial\"": 'middleName',
"\"Enter Last Name:\"": 'lastName',
"\"Enter UIN:\"":'uin',
"\"Are you attending the event?\"":'rsvp'
}
var lines = inputCsv.split('\n');
let [keys] = lines
keys = keys.split(',').splice(1,)
lines.splice(0,1);

var arrayCsv = [];
for (var line = 0; line < lines.length; line++){
const lineArray = lines[line].split(',').splice(1,).reduce((o,s,i) =>((o[keyMapping[keys[i]]] = s.replace(/"/gi, '').trim()),o),{});

// here i am creating object in desired format

let obj = {uin:lineArray['uin'],studentInfo:{firstName:lineArray}}

arrayCsv[line] = obj;
}


const outputJson = [];

console.log(arrayCsv);
}

convertToJson(inputCsv)

关于javascript - 如何净化在 javascript 中创建的结构化 json 文件的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54988857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com