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

时间:2015-09-02 09:39:23

标签: arrays json node.js

我试图读取我上传的xlsx find并尝试将数组数组转换为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'}
]

我怎样才能实现这一点......任何人都可以帮我解决这个问题

1 个答案:

答案 0 :(得分:2)

您可以重新解析生成的行并自己构建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;
});

或者您可以简单地使用为您执行此操作的模块,例如xlsx-json;

<强>更新

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

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