is super exercice for practicing Regex parsing.
lets take look of my code step by step :
// Create inline json with nested object.
const originalJson = `{dfkoz:'efzf','dd':"ddd",'zfzfzf','foo': {bar:1}}`;
then let split it in array by expected lines.
const lines = originalJson.replace(/[^,],+/g,"$&\n") \\ after each ',' let add '\n' after.
.replace(/{/g,"$&\n") // Add \n after any '{'
.replace(/}/g,"\n$&") // Add \n before any '}'
.split('\n'); // Split string to array with breakline separator
At this point you will have array like this :
0: "{"
1: "dfkoz:'efzf',"
2: "'dd':"ddd","
3: "'zfzfzf',"
4: "'foo': {"
5: "bar:1"
6: "}"
7: "}"
then you have to loop on it and add your tab and break line logic :
let formatedJson = '';
let nbrOfIndent = 0;
let previousNbrOfIndent = 0;
let isFindIndentMarker = false;
lines.forEach(line => {
previousNbrOfIndent = nbrOfIndent;
// if line is just { or finish by {, we have to increment number of \t for next loop iteration.
if(line === '{' || line.substr(-1) === '{') {
nbrOfIndent++;
isFindIndentMarker = true;
}
// if current line is just } or finish by , we have to decrease number of \t for next tick.
else if(line === '}' || line.substr(-1) !== ',') {
nbrOfIndent--;
isFindIndentMarker = true;
}
formatedJson += "\t".repeat((!isFindIndentMarker)?nbrOfIndent:previousNbrOfIndent) + line + "\n";
});
Online Sample