The Wayback Machine - https://web.archive.org/web/20240622161446/https://www.geeksforgeeks.org/how-to-convert-html-to-json-in-javascript/
Open In App

How to Convert HTML to JSON in JavaScript ?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript.

Below are the approaches to convert html to JSON in JavaScript:

Using html-to-json Library

In this approach, we are using the html-to-json library to parse and extract data from HTML. The library’s parse function takes HTML input and a mapping object defining how to extract data based on CSS selectors, converting it into structured JSON output.

Run the below command to install html-to-json Library:

npm install html-to-json

Example: The below example uses html-to-json Library to convert HTML to JSON in JavaScript.

JavaScript
const htmlToJson = require('html-to-json');
const html = `
    <div>
        <p>GFG</p>
        <p>Noida</p>
    </div>
`;
htmlToJson.parse(html, {
    description: function ($doc) {
        return $doc.find('div p:first-child')
                   .text();
    },
    location: function ($doc) {
        return $doc.find('div p:nth-child(2)')
                   .text().split(' ').pop()
                   .replace('(', '').replace(')', '');
    }
}).done(function (json) {
    console.log(JSON.stringify(json, null, 2));
});

Output:

{
"description": "GFG",
"location": "Noida"
}

Using DOM Parser

In this approach, we are using the xmldom library’s DOMParser to parse HTML content. We then traverse the parsed DOM structure using getElementsByTagName to extract specific elements and their text content. Finally, we format the extracted data into a JSON object.

Run the below command to install xmldom Library:

npm install xmldom 

Example: The below example uses DOM Parser to convert HTML to JSON in JavaScript.

JavaScript
const {
    DOMParser
} = require('xmldom');
const html = `
      <div>
          <p>GFG</p>
          <p>Noida</p>
      </div>
  `;
const doc = new DOMParser().parseFromString(html,
    'text/html');
const div = doc.getElementsByTagName('div')[0];
const paragraphs = div.getElementsByTagName('p');
const description = paragraphs[0].textContent;
const location = paragraphs[1].textContent.split(' ')
    .pop().replace('(', '')
    .replace(')', '');

const json = {
    description,
    location,
};
console.log(JSON.stringify(json, null, 2));

Output:

{
"description": "GFG",
"location": "Noida"
}


Similar Reads

Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript?
Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contains a form with input fields for name, email, and me
2 min read
How to convert JSON data to a html table using JavaScript/jQuery ?
Given an HTML document containing JSON data and the task is to convert JSON data into an HTML table.  These are the following approaches for converting the JSON data to an HTML table: Table of Content Using for loopUsing JSON.stringify() methodApproach 1: Using for loopTake the JSON Object in a variable.Call a function that first adds the column na
4 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
Difference between package.json and package-lock.json files
In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. In Node, package.json is a versioning file used to install multiple packages in your project. As you initialize your node application, you will see three files installed in your app that is node_modules, package.json, and package
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
three90RightbarBannerImg