I have implemented recursion to achieve this.
JSON data
let json = {
name: "John",
age: 30,
details: {
city: "New York",
country: "USA"
},
};
The following function will loop through the JSON object, encapsulate its keys and values within span tags, and separate them using JSON syntax tokens.
let json = {
name: "John",
age: 30,
location: "Earth",
details: {
city: "Los Angeles",
state: "California"
}
};
let styledJson = "<span class='syntax'>{</span><br/>" + formatJSON(json,24) + "<br/><span class='syntax'>}</span>";
document.write(styledJson);
function formatJSON(data, margin) {
var formattedData = '';
Object.entries(data).forEach(([key, value]) => {
formattedData += `<span style='margin-left:${margin}px;' class='json-key'>"${key}"</span><span class="syntax" ${this.scope}>:</span>`
if (typeof value == "object") {
formattedData += `<span class='syntax'>{</span><br/>`
formattedData += this.formatJSON(value, margin + 12)
formattedData += `<br/><span style='margin-left:${margin}px;' class='syntax'>}</span>`
} else {
if (Object.keys(data).reverse()[0] != key) formattedData += `<span class='value'>"${value}"</span><span class="syntax">,</span><br/>`
else
formattedData += `<span class='value'>"${value}"</span>`
}
})
return formattedData;
}
.json-key {
color: #7A01FF;
margin-left: 10px;
font-family: Consolas;
}
.value {
color: #F9D372;
font-family: Consolas;
}
.syntax {
color: #EEEEEE;
font-family: Consolas;
}
body {
background-color: #232932;
padding: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.5.4/typescript.min.js"></script>
Thank you