JSON Formatter
Given an input string representing a JSON object, print a string denoting the JSON object with the given format and indentation.
Formatting rule :
- Every opening brace should increase one indentation for the following lines.
- Every close brace should decrease one indentation for the same line and the following lines.
Examples :
Input: {“username”: “Jonas”, “email”: “[email protected]”} Output:
{
“username”: “Jonas”,
“email”: “[email protected]”
}
Input: {“username”: “Jonas”, “devices”:[“iPhone 13 Pro”, “Samsung Galaxy S30”]}
Output: {
“username”: “Jonas”,
“devices”:
[
“iPhone 13 Pro”,
“Samsung Galaxy S30”
]
}
Algorithm for JSON Formatter:
The basic idea is to iterate through the input JSON string character by character and keep track of the indentation level to format the output string correctly. Here’s a high-level approach:
Algorithm:
- Initialize an empty string to store the prettified JSON result.
- Initialize an indentation level (usually with a value of 0) to keep track of the current level of indentation.
- Loop through each character in the input JSON string.
- For each character:
- If it’s an opening curly brace { or an opening square bracket [, add a newline character, increase the indentation level, and add the character along with the appropriate number of indentation spaces or asterisks.
- If it’s a closing curly brace } or a closing square bracket ], add a newline character, decrease the indentation level, and then add the character along with the appropriate number of indentation spaces or asterisks.
- If it’s a comma ,, add a comma, a newline character, and the appropriate indentation.
- For any other character, simply add it to the result string.
- Continue this process until you’ve processed all characters in the input JSON string.
- Return the prettified JSON result.
Following is the implementation of the above algorithm:
C++
<?php
function prettifyJson( $s ) {
$indent = 0;
$r = "";
for ( $i = 0; $i < strlen ( $s ); $i ++) {
$x = $s [ $i ];
if ( $x === '{' ) {
$indent += 2;
$r .= $x . "\n" . str_repeat ( '*' , $indent );
} elseif ( $x === '[' ) {
$r .= "\n" . str_repeat ( '*' , $indent );
$indent += 2;
$r .= $x . "\n" . str_repeat ( '*' , $indent );
} elseif ( $x === '}' || $x === ']' ) {
$indent -= 2;
$r .= "\n" . str_repeat ( '*' , $indent ) . $x ;
} elseif ( $x === ',' ) {
$r .= $x . "\n" . str_repeat ( '*' , $indent );
} else {
$r .= $x ;
}
}
return $r ;
}
$s = '{"username":"Jonas","devices":["iPhone 13 Pro","Samsung Galaxy S30"]}' ;
echo prettifyJson( $s );
?>
|
Output
{
"username":"Jonas",
"devices":
[
"iPhone 13 Pro",
"Samsung Galaxy S30"
]
}
Time complexity – O(N) Auxiliary Space – O(N),N is the size of the JSON string.
|