帆:如何数组的数组转换为JSON对象

问题描述:

我想读我上传的XLSX找到并试图转换数组的数组JSON键值对的对象。
所以我想下面的代码片段

I'm trying to read my uploaded xlsx find and trying to convert array of array to json key value pair object. so i'm trying below snippet

var fs = uploadedFiles[0].fd;
var xlsxRows = require('xlsx-rows');
var rows = xlsxRows(fs);
var json = JSON.stringify(rows);
console.log(json);

这表明导致像数组的数组

It shows result like array of arrays

 [ [ 'Name', 'Age', 'Address' ],
  [ 'Raj', '43', 'trichy' ],
  [ 'Krthi', '23', 'trichy' ],
  [ 'vel', '24', 'trichy' ] ]

但我需要存储此作为重点淡水河谷对JSON对象的。

but i need to store this as a key vale pair of json object.

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

我如何能实现this..can任何一个可以帮助我解决这个问题。

how can i achieve this..can any one help me to fix this issue

您可以重新解析结果行并构建自己的JSON

You can either re-parse the resulting rows and build the JSON yourself

// 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;
});

或者你可以简单地使用一个模块,它会为你,就像 xlsx- JSON ;

更新

如果我用你的样本数据执行上述code,我得到正是你期待的输出,即(以获得输出JSON.stringify(结果)

If I execute the above code with your sample data, I get exactly the output you're expecting, namely (output obtained with JSON.stringify(result)):

[
  {
    "Name": "Raj",
    "Age": "43",
    "Address": "trichy"
  },
  {
    "Name": "Krthi",
    "Age": "23",
    "Address": "trichy"
  },
  {
    "Name": "vel",
    "Age": "24",
    "Address": "trichy"
  }
]