Is there a way to convert Excel data into JSON format and then automatically write it to a JSON file using Cypress?

After attempting to convert an excel file into json format using my code, I encountered some difficulties in obtaining the desired output. Instead of a proper conversion, it seems to return an array of each row. Any assistance in reading the data correctly and writing it to a json file would be greatly appreciated. Thank you in advance. Below is the relevant section of my code:

plugins/index.js file

const xlsx = require("node-xlsx").default;
const fs = require("fs");
const path = require("path");
module.exports = (on, config) => {
  on("task", {
    parseXlsx({ filePath }) {
      return new Promise((resolve, reject) => {
        try {
          const jsonData = xlsx.parse(fs.readFileSync(filePath));
          resolve(jsonData);
        } catch (e) {
          reject(e);
        }
      });
    }
  });
}

spec.js file

describe('API', () => {
    it('readf', () => {
        cy.parseXlsx("/Cypress/cypress/fixtures/data.xlsx").then(
            (jsonData) => {
                const rowLength = Cypress.$(jsonData[0].data).length
                for (let index = 0; index < rowLength; index++) {
                    console.log(jsonData[index].data)
                }
            }
        )
    }
)

My goal is to obtain a json output and write it to a json file structured as follows:

{
    "Sheet1": [
        {
            "Username": "user1",
            "password": "password1"
        },
        {
            "Username": "user2",
            "password": "password2"
        },
        {
            "Username": "user3",
            "password": "password3"
        }
    ]
}

Answer №1

When it comes to converting Excel sheets into JSON (and vice versa), I rely on the xlsx package provided by SheetJS.

const XLSX = require('xlsx');

// read file
let workbook = XLSX.readFile(filename);

// read first sheet (identified by first of SheetNames)
let sheet = workbook.Sheets[workbook.SheetNames[0]];

// convert to JSON
let json = XLSX.utils.sheet_to_json(sheet);

If you are working on a server application, be mindful that using 'xlsx' involves blocking methods which may lead to I/O waits in your process thread. It is recommended to run this operation asynchronously within a forked process.

Answer №2

When the user selects a file using the #ImportItemsInput element, this code snippet utilizes FileReader to read the selected file as an array buffer. Once the file is successfully loaded, it uses XLSX to process the data and extract information from the Excel workbook. The resulting JSON object is then stored in the variable 'json'.

Answer №3

Converting Excel to JSON directly and reading it in your code is not possible as the readFileSync function hits the browser, which is server-based.

To resolve this issue, I recommend checking out the solution provided in my repository linked below: "https://github.com/Achudan/ExcelToJsonConverterForCypress"

(We successfully used this method for our team - it's a simple solution compared to creating a separate Excel to JSON converter)

Simply run the node app on a port and use cy.request in your Cypress command.

For a detailed explanation, please refer to the Readme file in the above Github link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

Error message: "Unable to access D3 data when trying to select nested

Working with JSON data in D3 is proving to be a challenge for me. The file seems to be properly read, as indicated by its appearance when I use console.log, and it appears to be correctly formatted based on the examples I have come across. However, when I ...

Picture failing to show in browser despite successful upload using node

I am encountering some challenges while attempting to upload images using a node-express server. Two issues have come up. Firstly, the uploaded picture file lacks a proper extension and is given an auto-generated name like 2f22c2502b907f7bf0bc2567c43c801c ...

How can AngularJS service methods be assigned to controller $scope for use in an ng-repeat loop in the view?

As part of my development process, I decided to refactor my controller code in order to make it more reusable across multiple controllers. The original version of the controller (colorController.js) worked perfectly fine before I attempted to refactor it i ...

What could be causing this issue with my Mongoose.js program when it freezes during a 'nested' save operation?

[edit]: I made a revision to the previous question, providing a very precise reproducible example. This is the program I've created. I have developed two Schemas named ASchema and BSchema with collections A and B respectively. Then, I generated ...

Retrieve all the data enclosed within the span tags

Assuming there are two instances of tbody on a given page, is it possible to retrieve all the data enclosed within the spans of the second occurrence of tbody as shown below? The unique id's (id=id1, id=id2, etc) can only be found once throughout the ...

Transforming the appearance of an Imagebutton upon clicking with the power of Javascript

I am attempting to update the image URL when a specific image button is clicked, however, I am encountering an issue where the image does not change. It seems that none of the JavaScript functions are successfully altering the image and are unable to iden ...

What sets apart a string constant from a string enclosed in quotation marks? And what techniques exist to transform one into the other?

Calling an asynchronous function: const variable = 'something' await MyAsyncFunction.execute(variable) No output is displayed. But if I change it to: await MyAsyncFunction.execute('something') It works!! Can someone please explain h ...

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

Issues with webpage responsiveness, width not adjusting correctly

Just completed coding my website and now I'm facing a new challenge. I am focusing on making it responsive for tablet screens (768px) starting with the header section, but for some reason, the modifications I make in the responsive.css file are not ta ...

Error Message: "Duplicate variable declaration detected"

This piece of code is causing me some major headaches. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#" data-source="ryedai">Ryedai</a> <a href=&q ...

Issue encountered while retrieving JWT

Currently, I am tackling the challenge of implementing JWT authentication using Angular and Java Jersey. I have successfully managed to send the JWT token from the server to the client, which can be observed as a POST response with a status code of 200 in ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

What makes long polling to an asp.net mvc app necessitate using the POST instead of GET ajax method?

Currently, my team and I are working on replicating a demo app showcased by Steven Sanderson in his SignalR demonstration, specifically focusing on the long polling feature. While the demo is functioning properly, we have encountered an issue when switchin ...

Converting JSON to an object in C# using WebRequest

I am encountering an issue while attempting to convert this JSON into an object of a specific class. The error I receive is: ":" or "{" expected. Below is the JSON in question: {"data":[{"id":"https:\/\/api.cognitive.microsoft.com\/api&bso ...

"Encountering a Bad Request Error When Setting Up Power Automate Flow for SharePoint List and Azure DevOps Work Item Integration due to an

I have set up a Power Automate flow to track modifications made on a SharePoint List: https://i.stack.imgur.com/jMDbA.png Here is the response body I receive from the wiql query: https://i.stack.imgur.com/mlWtn.png In order to update the work item if i ...

Double firing of beforeUpdate event observed in Vue for recursive components

Recently delving into the world of vue js, I've been tinkering around with a recursive tree example inspired by the official example found here. While the original example starts with treedata containing a single root and multiple children, my goal w ...

Ensuring that an object attribute is assigned to $watch in AngularJS to activate triggering

As a newcomer to AngularJS, I recently attempted the following code: <div ng-controller="ctrl1"> <div ng-controller="ctrl2"> <select ng-model="myvar" ng-options="c for c in vars" ></select> <div>{{myvar}} ...