@mthdht/json-to-html-parser v1.0.0
Table of Contents
About The Project

This package is a simple class that allows you to convert Html elements as Json format into a html string
A element is represented by 4 attributes: tag - attributes - content - children (see Usage)
Getting Started
Prerequisites
- npm
npm install npm@latest -gInstallation
- Install NPM packages
npm install @mthdht/json-to-html-parserUsage
First you have to import the newly installed package, then use it in your code
import JsonConverter from '@mthdht/json-to-html-parser' // as ES6 module or,
let JsonConverter = require('@mthdht/json-to-html-parser') // as node js module
// Your code ...
let result = JsonConverter.convertToElement(SomeJsonRepresentationOfElements)The Json data that you pass into the convertToElement method must some rules:
- It must have a root element
- There are 4 main attributes to represent a html element (see Examples):
tag: The name of the element (required except if only havecontentattribute)attributes: An object of the element attributes. eg: { 'class': 'some class', ...} (optional)content: The texte content of the element (optional but cannot be used withchildrenattribute)children: An array of children elements (optional)
Examples
For a simple element
{
'tag': 'p',
'attributes': {
'class': 'classe1 classe2 ...',
'title': 'Some title',
...
},
'content': 'My p content'
}Using JsonConverter.convertToElement on this json representation will return a string that looks like this:
<p class="classe1 classe2 ..." title="Some title" ...>My p content</p>You can build nested elements by using the children attribute. It must be an array with all nested elements you want
{
'tag': 'div',
'attributes': {...},
'children': [
{
'tag': 'element1'
...
},
{
'tag': 'element2,
...
}
]
}Will return some string like this:
<div atribute1="value1" ...>
<element1 ...>...</element1>
<element2 ...>...</element2>
</div>Sometimes you may wish having an element with text content surrounded by other elements like span, strong etc...
In this case, you can use an object with only the content attribute in the children attribute like this:
{
'tag': 'element',
'attributes': {...}, // if needed
'children': [
{
'content': 'The text content'
},
{
'tag': 'span,
'content': 'Some Span Content'
}
]
}will return this:
<element ...>
The text content<span>SomeSpan Content</span>
</element>Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature) - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
License
Distributed under the MIT License.
Contact
Mthdht - @mthdht - mthdht@gmail.com
Project Link: https://github.com/mthdht/json-to-html-parser
7 years ago