gpt4 book ai didi

javascript - 数组数组转 Json

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:09 26 4
gpt4 key购买 nike

我正在循环将数组的数组转换为对象,我使用逗号“,”进行分割,但如果我的值有一些逗号,它也会被分割。例如:如果我的值的日期为 2017 年 5 月 2 日,它实际上是一个值,但它被拆分为 5 月 2 日作为一个值,2017 年作为另一个值,因此,我的整个对象正在更改。需要帮助

我正在读取 Excel 工作表。我的输出是数组的数组。我需要将其转换为 json 对象。

var xls = require('excel');
describe('TransactionDetails-Excel', function () {
it('External Type G Tranasaction Details validation', function (done) {
xls('transactions.xlsx', function(err, data) {
if(err){
throw err;
}
else{
console.log(data);
console.log(JSON.stringify(convertToJSON(data)));
done();
}
});
function convertToJSON(array) {
var first = array[0].join();
var headers = first.split(',');
var jsonData = [];
for ( var iterator_i = 1, length = array.length; iterator_i < length; iterator_i++ ){
var myRow = array[iterator_i].join();
var row = myRow.split(',');
var data = {};
for ( var x = 0; x < row.length; x++ ){
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
}
});
});

Excel 工作表:transactions.xlsx click here to view screenshot of excel sheet

输出:数据

[ [ 'Transaction Id', 'Paid ', 'Time Created' ],
[ '0YC0',
'Joe\'s Generic Business \nperson@gmail.com',
'Mar 2, 2012 14:28:36 PST' ],
[ '8uyhr', 'mail@gmail.com', 'May 2, 2015 15:20:20 PST' ],
[ '786YUH', 'mailtome@gmail.com', 'May 18, 2017 13:20:30 PST' ] ]

输出://这就是我得到的

[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \nperson@gmail.com","Time Created":"Mar 2","undefined":" 2012 14:28:36 PST"},   
{"Transaction Id":"8uyhr","Paid ":"mail@gmail.com","Time Created":"May 2","undefined":" 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"mailtome@gmail.com","Time Created":"May 18","undefined":" 2017 13:20:30 PST"}]

但最终对象应该是:

[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \nperson@gmail.com","Time Created":"Mar 2, 2012 14:28:36 PST"},   
{"Transaction Id":"8uyhr","Paid ":"mail@gmail.com","Time Created":"May 2, 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"mailtome@gmail.com","Time Created":"May 18, 2017 13:20:30 PST"}]

提前致谢。

最佳答案

使用已安装的函数

function convertToJSON(array) {
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}

return objArray;
}

关于javascript - 数组数组转 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44173385/

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