帆:如何数组的数组转换为JSON对象 [英] sails:how to convert array of array to json object

查看:117
本文介绍了帆:如何数组的数组转换为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"
  }
]

这篇关于帆:如何数组的数组转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆