Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to convert JPG to PNG using Node.js ?
Next article icon

How to convert tabular string to JSON using Node.js ?

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Tabular: Information that is displayed in a table with rows and columns is known as "tabular format". A data table is an organized and practical approach to displaying a significant amount of information that contains repeated data items. The majority of office productivity software packages, including word processing software and spreadsheets, have capabilities for text and data entry in tabular format.

Example:

<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
</tr>
</tbody>
</table>

JSON: JavaScript Object Notation, or JSON. It is a text-based data transfer format that preserves the data's organizational structure.  It supports data structures that are quickly executed on the server, such as arrays, objects, and JSON documents. It is also a JavaScript-derived language-independent format. JSON files should be saved with the .json extension and the application/json media type.

Example:

[
[
{ 'Column 1': 'A1', 'Column 2': 'A2', 'Column 3': 'A3' },
{ 'Column 1': 'B1', 'Column 2': 'B2', 'Column 3': 'B3' },
{ 'Column 1': 'C1', 'Column 2': 'C2', 'Column 3': 'C3' }
]
]

Approach: We need one NPM Package for converting tabular format or string to JSON named "tabletojson".

npm install tabletojson

The method convert() and convertUrl() in this package allows us to pass the markup for a single table as a string, a chunk of HTML, a whole page, and just a URL (with an optional callback function; promises are also supported). Every time, an array is a response. A table from the page is represented by each array entry in the response (in same the order they were found in the HTML).

Example 1: In this example, we will be using convertUrl() with a remote URL that contains any tabular form data for demonstrating the conversion of the table to JSON. First, We will be importing a class from tabletojson module named Tabletojson class and storing it into a variable called tabletojson. This convertUrl() method will be called from this class reference variable. This convertUrl() method will take two parameters as given below: 

Parameters:

  • The first parameter will be a remote URL or Web URL which contains any tabular form data.
  • The second Parameter will be a callback function that will get executed after the completion of the conversion of tabular format data to JSON successfully. 

Project Structure: It will look like the following. 

ou

app.js

JavaScript
const tabletojson = require('tabletojson').Tabletojson;  tabletojson.convertUrl(     'https://en.wikipedia.org/wiki/Tata_Consultancy_Services',     function (tablesAsJson) {         console.log(tablesAsJson[1]);     } ); 

Step to run the application: Open the terminal and type the following command. 

node app.js


Example 2: In this example, we will use a local HTML file that contains some data in tabular format for demonstrating an example of the conversion of the table to JSON data. First, We need to import the class Tabletojson from tabletojson module in the app.js file. In this class, there is a method convert which we will be using for converting tabular data to JSON. Before, starting the implementation of code, we need to understand two methods that we will use in implementation. The first method is fs.reafFileSync() and the Second method is path.resolve(). Below, briefly explained both methods with their syntax, parameters and it's return values. 

Using fs.readFileSync() method: The fs module includes an application programming interface (API) called fs.readFileSync() that can be used to read files and return their contents. 

Syntax:

fs.readFileSync( path, options )

Parameters:  

  • path: It uses the text file's relative path. A URL-type path is also possible. Additionally, the file may be a file descriptor. Just put the filename in quotes if both files are in the same folder.
  • options: It is an optional parameter that contains an encoding, a flag, and a data definition in the encoding. Its default value of null returns a raw buffer, and the flag includes information about file actions. 'r' is the default value for it.

Return Value: This method will return the content of the file.

Using path.resolve() method: A series of route segments can be resolved to an absolute path using the path.resolve() method. It operates by prepending each of the paths in the right-to-left order of the paths until the absolute path is produced. The resulting path is normalized, and any necessary trailing slashes are taken out. 

Syntax:

path.resolve( [...paths] )

Parameters:

  • paths:  It consists of a collection of file paths that would be combined to make an absolute path. If this parameter's value is not a string, a TypeError is raised.

Return Value: This method will return a string with an absolute path.

Project Structure:

table.html file: Using this HTML file for sample data for showing demonstration in the example. 

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport"          content="width=device-width, initial-scale=1.0">     <title>GeeksforGeeks</title> </head>  <body>     <table>         <thead>             <tr>                 <th>Column 1</th>                 <th>Column 2</th>                 <th>Column 3</th>             </tr>         </thead>         <tbody>             <tr>                 <td>A1</td>                 <td>A2</td>                 <td>A3</td>             </tr>             <tr>                 <td>B1</td>                 <td>B2</td>                 <td>B3</td>             </tr>             <tr>                 <td>C1</td>                 <td>C2</td>                 <td>C3</td>             </tr>         </tbody>     </table> </body>  </html> 

app.js file: 

JavaScript
const tabletojson = require('tabletojson').Tabletojson; const fs = require('fs'); const path = require('path');  const html = fs.readFileSync(path.resolve(__dirname, 'table.html'),     { encoding: 'UTF-8' }); const converted = tabletojson.convert(html);  console.log(converted); 

Output:


Next Article
How to convert JPG to PNG using Node.js ?

S

shubhanshuarya007
Improve
Article Tags :
  • Technical Scripter
  • Web Technologies
  • Node.js
  • Technical Scripter 2022
  • NodeJS-Questions

Similar Reads

  • How to Convert PNG to JPG using Node.js ?
    The following approach covers how to convert PNG to JPG in Node.js using Jimp module. Jimp is an image processing library that we can use to do a lot of operations on images. Jimp stands for JavaScript Image Manipulation Program. ApproachTo convert PNG to JPG using Node.js. We will Import Jimp modul
    2 min read
  • How to convert JPG to PNG using Node.js ?
    Converting images between different formats is a common requirement in web development. Node.js, with its powerful libraries and ecosystem, makes it easy to perform such tasks. This article will show you how to convert a JPG image to PNG using Node.js, covering both the basic and more advanced techn
    2 min read
  • How to convert an object to string using JavaScript ?
    To convert an object to string using JavaScript we can use the available methods like string constructor, concatenation operator etc. Let's first create a JavaScript object. [GFGTABS] JavaScript // Input object let obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact: 248
    4 min read
  • How to Convert String to JSON in TypeScript ?
    Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript: Table of Content Convert String to JSON Using JSON.parse()Convert String
    6 min read
  • How to Convert JSON to string in JavaScript ?
    In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used
    3 min read
  • How to Parse JSON using Node.js?
    JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configu
    2 min read
  • How to Convert String to JSON in JavaScript?
    In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
    2 min read
  • How to Convert an Object to a JSON String in Typescript ?
    In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
    5 min read
  • How to Convert a Map to JSON String in JavaScript ?
    A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of Content Using Object.fromEntries() MethodUsing
    2 min read
  • How to export HTML table to CSV using JavaScript ?
    Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications. Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file c
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences