Contents:

Free Python course ➞ A mini-course for beginners and experienced coders. Four cool projects in the portfolio, live communication with the speaker. Click and find out what you can learn in the course.
Learn moreHTML and the JSON data format have important similarities in structuring information, but their application in web development differs. HTML serves as the basis for displaying website markup, providing a visual representation of content for users. JSON, meanwhile, is used to exchange data between the client and server, providing a convenient and lightweight way to transfer information. Thus, both tools play a key role in creating functional and interactive web applications.
By sending information from the server in JSON format, we ensure its independence from the way it is displayed on the user's device. This approach allows users to interact with data in various environments: a native mobile app, a command-line utility, or a web browser. Furthermore, displaying data correctly in a browser often requires complex JavaScript logic, which cannot be integrated into generated HTML code. Using JSON simplifies the data transfer process and improves the user experience, allowing developers to create more flexible and responsive applications.
Libraries for working with JSON are available in virtually all modern programming languages, confirming the versatility of this format. JSON stands for JavaScript Object Notation, which explains the presence of built-in methods for working with JSON in JavaScript. JSON syntax almost completely matches the structure of JavaScript objects, making this language ideal for working with this format. JSON is widely used for exchanging data between clients and servers, confirming its importance in web development and programming in general.
Where is this JSON of yours found?
Many web developers prefer to generate HTML code in JSON format upon request from the frontend. This code is then converted to standard HTML markup directly in the browser. A similar approach is used on our website, Skillbox Media, which we discussed in detail in our article on data parsing. Using JSON to transfer HTML code optimizes page loading and improves user experience.

The Reporters Without Borders website implements a similar method for loading additional articles in various country categories. Let's look at Italy, for example. Clicking the "Show more posts" button loads three earlier articles. If you follow the link, you'll see a JSON insert containing the article code inside the element. This approach allows users to easily access archived materials, improving navigation and interaction with content.


Converting HTML to JSON is a simple task if you understand the key aspects of both formats. We'll start this article by covering the basic characteristics of HTML and JSON, then build a small application that efficiently converts between the two formats. Understanding these features will help you avoid common mistakes and simplify the conversion process.
A Brief Introduction to the Difference Between HTML and JSON
A website's HTML markup consists of elements consisting of three main parts: the opening tag, the closing tag, and the content. Each element plays a key role in the structure of a web page. The opening tag marks the beginning of an element, the closing tag ends it, and the content represents the information the element contains. Proper HTML structure is essential for creating effective and optimized web pages, which contributes to a better user experience and improves a website's ranking in search engines.
The HTML opening tag can contain various attributes, specified in the format attribute=»value». These attributes provide additional information about the element and determine its behavior or appearance on the web page. Proper use of attributes improves SEO and makes the site more user-friendly. For example, attributes such as alt for images or title for links help search engines better index content. Key attributes such as class and id allow you to apply styles and scripts, improving the user experience.
JSON has its own unique structure: it is a set of key: value pairs. Each pair includes a key and a value, which are enclosed in quotation marks. The key is followed by a colon, and the pairs themselves are separated by commas. All this information is packaged in curly braces. JSON is a popular format for exchanging data due to its simplicity and readability. JSON markup can accommodate various value types, such as numbers, strings, Booleans, objects, arrays, and null. This knowledge will be useful later when we create examples containing objects and arrays. JSON (JavaScript Object Notation) is a convenient format for exchanging data and is often used in web development and APIs. Understanding the structure of JSON will help you work effectively with data and integrate it into your projects. A final comma before the closing parenthesis is not allowed in JSON. Trailing commas are not allowed in JSON. This is an important rule to keep in mind when working with JSON to avoid errors when parsing data. Proper use of commas helps ensure that the data is correctly structured and can be processed successfully.
The differences between HTML and JSON may seem significant at first glance, but in practice, converting HTML to JSON is quite simple. Let's look at the process in more detail.
HTML (HyperText Markup Language) is a markup language used to create web pages. It consists of various tags that define the structure and content of the document. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easily read by humans and easily parsed by machines.
When converting HTML to JSON, you must take into account the data structure to preserve the information in an easy-to-process format. Each HTML element can be represented as a JSON object, where tags become keys and their contents are values.
Thus, converting HTML to JSON requires a careful approach, but it is quite feasible. By following a clear schema and syntax rules, you can efficiently convert data while preserving its structure and semantics.
Each HTML element can be converted to a JSON structure in the format "key": "value". In this format, the key is the element's name, and the value is the text content of the element or the next-level nested element. This approach allows HTML content to be easily integrated into systems that use JSON, simplifying the processing and transmission of data in web applications.
Now we'll look at how to implement similar functionality using JavaScript on a single website page. Using JavaScript allows you to create interactive elements, improve the user experience, and optimize interaction with content. We'll use simple scenarios to demonstrate how JavaScript can be effectively embedded in a web page, creating dynamic changes and improving the overall structure of the site.
Converting
The process of converting data to JSON format is called serialization, and the reverse process is called deserialization. There are two main methods for converting HTML markup to JSON.
- Convert the markup "brainlessly", cramming all the HTML code into a single key: value pair - that is, as the value of the key, (as in the screenshot of the Skillbox Media markup).
- Write a more complex version of JSON so that the structure of the JSON string fully corresponds to the structure of the HTML document.
The choice of implementation method depends on your tasks. For educational purposes, we will look at a more complex second method, which will allow us to explore the capabilities of the JavaScript language and preserve the page structure. Consider the following code example:
An HTML page template includes basic components, such as utility elements and content located in the page body. It is important to note that some elements may contain attributes and nested elements that must be taken into account during conversion. Correct use of these components ensures the correct display and functionality of the web page, which is important for SEO optimization and user experience.
Let's return to the common situation shown in the first screenshots: the page structure remains static, while when loading data from the server, only the content of the page body changes, which should be passed to the JSON converter. Therefore, the main focus should be on the content of the element. This allows for efficient data processing and optimized interaction with the server, which is important for improving the user experience and increasing page loading speed.
The current page contains several arbitrary paragraphs and an image. Our training converter offers versatile capabilities and can convert not only text paragraphs but also any other HTML elements, including elements nested up to three levels, into JSON. This makes it an ideal tool for working with various content formats, providing convenience and flexibility in data processing. The workflow is as follows: first, you need to define the goal and objectives to be addressed. Then, you should analyze the current situation to identify key points and potential problems. After this, you can begin developing a strategy that will include specific steps and actions. It is also important to establish criteria for evaluating results so that you can subsequently adjust your actions based on the data obtained. The final stage will be the implementation of the developed plan and monitoring its effectiveness.
- Let's create a JavaScript object for writing HTML elements, their attributes, and content.
- Write each element to the object one by one.
- Convert the object to JSON format.
We'll cover these steps in detail in the next section, but first, we need to create two files.
- We'll call the first one "HTML to JSON.html" (the link to the file contents on the Pastebin service) and place the actual page to be converted in it.
- The second one will be called "script.js" (the link to the file contents on the Pastebin service) - we'll place the page-to-JSON converter written in JavaScript in it.
The script will be activated after the page has fully loaded, so we'll place the corresponding element in the body of the HTML document. This will ensure correct script execution and improve user experience. Proper integration of the script into the HTML code helps optimize page loading and improves overall website performance.

Now that we have imagined the desired result, let's take a closer look at the implementation process. The loop for iterating over HTML elements should break them down into their component parts, like Lego pieces. The following properties will help you find the component parts efficiently:
- tagName will find the names of the elements;
- attributes will return a collection of the element's attributes, while calls to attributes.name and attributes.value will return the names and values of individual attributes;
- to get nested elements of any level and text, you will need the children and textContent properties, respectively.
At each level of nesting of HTML elements, their number is first counted, and then iterated over using a for loop. This approach allows you to efficiently process the document structure, ensuring optimization of work with elements and improving script performance. Proper code organization and the use of loops help simplify manipulation of HTML elements and make the process more manageable.
In this context, we will use the length property to determine the number of HTML elements or attributes. This will help us effectively analyze the document structure and identify key elements, which is important for optimization and improving SEO. Proper management of HTML elements and attributes helps improve the visibility of a website in search engines.
The variable name e is a convenient shorthand for the word "element." However, you can choose any name that is more understandable and convenient for you.
Writing element names in HTML is a simple process. To do this, you need to get a collection of child elements and iterate over them using the ordinal number of the e element. Next, to extract the name of each element, you should access the tagName property. This will allow you to efficiently obtain the names of all child elements and use them later for analysis or data processing. Proper use of these methods helps optimize work with the DOM and improves interaction with elements on the page.
In this context, we create clear and understandable key names using a combination of text in quotation marks and the names of the corresponding variables enclosed in square brackets. This helps improve the structure of the code and makes it easier to understand. Proper key naming facilitates more efficient data handling and simplifies processing.
When working with attributes, it's necessary to pre-check an element for their presence. This is an important step that helps avoid errors and ensure proper interaction with page elements. Checking for attribute presence forms the basis for subsequent operations, such as reading or modifying them. Without this check, you may encounter issues related to missing or incorrect attributes, which can negatively impact the functionality of the web page. Therefore, it's important to always consider this aspect when developing and optimizing code.
The converter's response depends on the results of attribute checking. If attributes are detected, their number must be counted, each must be processed sequentially, and carefully placed in the designated location. This approach will ensure the correct display of data and improve the efficiency of the converter.
To iterate over attributes, a separate nested loop is used, in which the variable a denotes "attribute".
If no attributes are found, an empty value must be set.
After specifying the attributes, it is necessary to add the element's content, which can include text, nested elements, or remain empty. To do this, it is important to first determine the number of nested elements. If there are no nested elements, the next step is to check for the presence of text. This process can be performed as follows:
After the check is completed, the detected content of the first-level element is recorded. This process is important to ensure the accuracy and integrity of the data. Recording information at this stage allows you to save the analysis results and prepare them for further processing or use.
If the content consists of second-level elements, it is important to structure them correctly for ease of perception and optimization for search engines. Second-level elements play a key role in organizing information on a page, helping users and search engines more easily navigate the content structure. Ensure your headings and subheadings clearly reflect your content, effectively highlighting key topics and subtopics. This approach will not only improve user experience but also increase your page's visibility in search engines. Optimizing your text for SEO is an important aspect of content marketing. If you're working with text-based content, consider keywords that can increase your content's visibility in search engines. It's important that the text is not only informative but also easy to read. Structure your text using subheadings and lists to enhance its comprehension. Also, don't forget about internal and external links, which help users find additional information. Making sure your text is unique and relevant to your target audience will significantly increase your chances of successful online promotion.
Если отсутствует содержание, это может негативно сказаться на восприятии страницы пользователями и поисковыми системами. Наполнение сайта уникальным и качественным контентом является ключевым фактором для привлечения аудитории и улучшения позиций в поисковой выдаче. Без текста или информации посетители могут покинуть страницу, не найдя необходимую информацию. Поэтому важно обеспечить наличие информативного и релевантного контента на сайте, который отвечает на запросы пользователей и соответствует их ожиданиям. Это улучшит пользовательский опыт и повысит вероятность возвращения на сайт.
Элементы второго и третьего уровней добавляются аналогично при переборе содержимого их родительских элементов первого уровня. Это можно подробно рассмотреть на примере в финальной версии кода. Такой подход обеспечивает структурированность и упрощает процесс работы с вложенными элементами.
Второй и третий уровни используют собственные циклы for для перебора элементов. В этих циклах применяются переменные e2 и e3, а для обхода атрибутов используются переменные a2 и a3, аналогично первому уровню. Такой подход обеспечивает упорядоченную и эффективную обработку данных на каждом уровне.
После завершения циклов перебора и записи объектов элементов на всех уровнях, включая их атрибуты и содержимое, мы передаем полученный JavaScript-объект встроенному методу JSON.stringify(). Этот метод выполняет сериализацию объекта, преобразуя его в строку формата JSON, что позволяет удобно сохранять или передавать данные. Использование JSON.stringify() обеспечивает совместимость с различными системами и позволяет легко работать с данными в различных приложениях.
Для вывода результата на страницу необходимо использовать команду, которая перезаписывает содержимое элемента с помощью значения переменной result. Убедитесь, что элемент, который вы хотите изменить, правильно идентифицирован, чтобы обновление прошло успешно.
Итоговый код доступен для просмотра и копирования по предоставленной ссылке. После его выполнения ваша страница преобразуется в JSON-строку и будет выглядеть следующим образом:
В любом JSON-форматтере можно увидеть результат в более удобочитаемом формате. Эти инструменты позволяют пользователям легко анализировать и редактировать JSON-данные, улучшая восприятие структуры информации. JSON formatting makes code more understandable, which is especially important for developers and data scientists. Использование JSON-форматтеров значительно упрощает взаимодействие с данными, позволяет быстро находить ошибки и повысить эффективность работы с API и другими источниками данных.

To verify the correctness of the result, we also use a JSON validator. This will help ensure that the data complies with format standards and is error-free. Применение валидатора JSON является важным шагом в процессе разработки, так как он позволяет выявить возможные проблемы и гарантирует, что информация будет правильно обработана в дальнейшем.

В консоли вы увидите впечатляющий вывод.

Итоги
В данной статье мы обсудили один из методов преобразования HTML-файла в JSON-строку. Существует множество подходов к реализации этой задачи, и конкретный код будет варьироваться в зависимости от ваших требований. Следуя предложенному алгоритму и используя встроенные функции JavaScript, вы сможете создать свой собственный конвертер. В следующем материале мы расскажем, как выполнить обратное преобразование из JSON в HTML.
Изучите также:
- Как отсортировать массив в PHP тринадцатью способами: инструкция с примерами
- Идти в IT, не зная информатики: а что, так тоже можно было?
- 16-летний веб-разработчик: «Я мечтал стать программистом с 11 лет»

