Image for post
Image for post

Writing a JSON to Bootstrap grid parser using recursion

Suppose you have an API (returns JSON) and you need to a get Bootstrap Grid layout through the API. Also think!.. the properties of the layout(column data, color etc.) are managed by the API. So what strategy you follow? 🤔 How about responding row-column information from API as a json Object😋.

We need kind of standard for the json format. We can store row and column as json objects. and rows, columns objects can be stored in a json array.

{
rows: [
{
columns: [
{
text: 'col 1',
width: 6,
color: 'green'
},
{
text: 'col 2',
width: 6,
color: 'yellow'
}
]
}
]

}
Image for post
Image for post
Output for above JSON

We can convert above structure simply by implementing straight forward logic. But what happen if there are nested rows and columns like this.

{
rows: [
{
columns: [
{
width: 6,
rows: [
{
columns: [
{
width: 12,
rows: [
{
columns: [
{
width: 6,
text: 'col',
color: 'lightblue'
},
{
width: 6,
text: 'col',
color: 'lightgreen'
}
]
}
]
}
]
},
{
columns: [
{
width: 12,
color: 'red',
text: 'col'
}
]
}
]
},
{
width: 6,
color: 'yellow',
text: 'col'
}
]
}
]
}
Image for post
Image for post
Output for above JSON

So!.. nested elements. rows inside columns and then columns inside those rows. What we can do? Indeed top-down recursion strategy can be used.

For each element div tags need to be created and inside the tags nested div tags need to be created.

I wrote this Javascript class and the function for parsing JSON to grid layout.

class Parser {
createRow(r) {
return '<div class="row">' + this.parse(r) + '</div>';
}
createColumn(c) {
return '<div style="background-color : ' +
c.color + '" class="col-lg-' + c.width + '">' +
(c.text ? c.text : '') + this.parse(c) + '</div>';
}
parse(s) {
let S = '';
if (s.rows) {
for (let i in s.rows) {
S += this.createRow(s.rows[i]);
}
}
if (s.columns) {
for (let i in s.columns) {
S += this.createColumn(s.columns[i]);
}
}
return S;
}
}
let json2bootgrid = (inputJson) => {
return new Parser().parse(inputJson);
}

parse method takes a json object and construct the final html source of the entire grid. createColumn and createRow methods are responsible for rendering columns are rows respectively. And each method calls theparse method recursively by passing the given json since there may be nested elements and those elements need to rendered as well.

I published the source and the demo in to Github. Give an issue or a PR, Obviously a star ⭐

Happy Parsing! 🤩

Written by

Software Engineer at 99x | Apache PMC member | Open Source Contributor (Author of Neutralinojs) | Technical Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store