Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays sails:如何将数组的数组转换为json对象_Arrays_Json_Node.js - Fatal编程技术网

Arrays sails:如何将数组的数组转换为json对象

Arrays sails:如何将数组的数组转换为json对象,arrays,json,node.js,Arrays,Json,Node.js,我正在尝试读取上传的xlsx查找,并尝试将数组数组转换为json键值对对象。 所以我在下面的片段中尝试 var fs = uploadedFiles[0].fd; var xlsxRows = require('xlsx-rows'); var rows = xlsxRows(fs); var json = JSON.stringify(rows); console.log(json); 它显示的结果类似于数组的数组 [ [ 'Name', 'Age', 'Address' ], [ '

我正在尝试读取上传的xlsx查找,并尝试将数组数组转换为json键值对对象。 所以我在下面的片段中尝试

var fs = uploadedFiles[0].fd;
var xlsxRows = require('xlsx-rows');
var rows = xlsxRows(fs);
var json = JSON.stringify(rows);
console.log(json);
它显示的结果类似于数组的数组

 [ [ 'Name', 'Age', 'Address' ],
  [ 'Raj', '43', 'trichy' ],
  [ 'Krthi', '23', 'trichy' ],
  [ 'vel', '24', 'trichy' ] ]
但我需要将其存储为json对象的密钥值对

[{'Name':'Raj',
'Age':'43',
'Addess':'tichy'},
{'Name':'Krthi',
'Age':'23',
'Addess':'tichy'},
{'Name':'Vel',
'Age':'24',
'Addess':'tichy'}
]

我怎样才能做到这一点。有人能帮我解决这个问题吗?

您可以重新解析生成的行,然后自己构建JSON

// your existing code
var fs = uploadedFiles[0].fd;
var xlsxRows = require('xlsx-rows');
var rows = xlsxRows(fs);

// retrieve headers (i.e. remove first row)
var headers = rows.shift();

// then build the json for each row
var result = rows.map(function(row) {
    var jsonRow = {};
    row.forEach(function(cellValue, cellIndex) { 
        jsonRow[headers[cellIndex]] = cellValue;
    });
    return jsonRow;
});
或者你可以简单地使用一个模块为你做这件事,比如

更新

如果我使用您的示例数据执行上述代码,我将获得您所期望的输出,即(使用
JSON.stringify(result)
获得的输出):


它显示了一个类似TypeError的错误:Object[[“Name”、“Age”、“Address”]、[“Martin”、“43”、“trichy”]、[“Krthi”、“23”、“trichy”]、[“vel”、“24”、“trichy”]]没有方法“shift”我的错,我使用了错误的变量,它应该是
行,而不是
json
。很肯定有办法。无论如何,您仍然可以使用上面的代码使其以您喜欢的方式工作。Val再次将其存储为json数组而不是对象。因此,我需要json对象。请提供帮助。对此不确定,对我来说效果很好,请查看我上面得到的输出,它符合您的期望。
[
  {
    "Name": "Raj",
    "Age": "43",
    "Address": "trichy"
  },
  {
    "Name": "Krthi",
    "Age": "23",
    "Address": "trichy"
  },
  {
    "Name": "vel",
    "Age": "24",
    "Address": "trichy"
  }
]