2

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' ] ]

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'}
]

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

1 Answer 1

3

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

Or you can simply use a module that does it for you, like xlsx-json;

UPDATE

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"
  }
]
Sign up to request clarification or add additional context in comments.

5 Comments

It shows an error like TypeError: Object [["Name","Age","Address"],["Martin","43","trichy"],["Krthi","23","trichy"],["vel","24","trichy"]] has no method 'shift'
My bad, I used the wrong variable, it should be rows instead of json.
Pretty sure there's a way. Anyway, you can still use the above code to make it work the way you like.
Val its again store as a json array not an object.I need json object as a result.please help.
Not sure about it, works fine for me, see the output I get above, which matches what you're expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.