Member-only story

Simplify JSON Formatting with Template Literals

A Better Way to Handle Complex Object Structures

Max N
2 min readApr 1, 2024

JavaScript object notation (JSON) has emerged as the de facto standard for transmitting structured data over networks since its formalization in the late 2000s. Its simplicity, lightweightness, and wide browser support made it an ideal choice for APIs, configuration files, and serialization tasks.

Despite being ubiquitous, working with JSON remains challenging due to verbosity, lack of indentation, and intricate hierarchies. Although libraries exist to alleviate some of these pain points, understanding native techniques can prove beneficial in specific situations.

Today, I’ll showcase how template literals streamline JSON formatting and bring clarity to otherwise convoluted structures.

Let’s begin with the basics. Imagine you wish to display a list of items fetched from an external source. Traditional methods would involve looping through arrays and concatenating strings via plus signs (+):

const items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }];
let itemList = '';
items.forEach((item) => {
itemList += `<li>${item.id}: ${item.name}</li>\n`;
});
document.getElementById('list').innerHTML = itemList;

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet