Horje
Algorithm for JSON Formatter without using external library

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; // Indentation level.
    $r = ""; //Result string.
   
    // Iterate over the characters in the JSON string.
    for ($i = 0; $i < strlen($s); $i++) {
        $x = $s[$i];
          // If we encounter a '{', we increase the indentation level.
        if ($x === '{') {
            $indent += 2;
            $r .= $x . "\n" . str_repeat('*', $indent);
          // If we encounter a '[', we add newline character and add [ and then increase the indentation level.
        } elseif ($x === '[') {
            $r .= "\n" . str_repeat('*', $indent);
            $indent += 2;
            $r .= $x . "\n" . str_repeat('*', $indent);
          // If we encounter a '}' or ']', we decrease the indentation level.
        } elseif ($x === '}' || $x === ']') {
            $indent -= 2;
            $r .= "\n" . str_repeat('*', $indent) . $x;
          // If we encounter a ',', we add a newline and indent the next line.
        } elseif ($x === ',') {
            $r .= $x . "\n" . str_repeat('*', $indent);
          // Otherwise, we just add the character to the output string.
        } else {
            $r .= $x;
        }
    }
 
    return $r;
}
 
// Example
$s = '{"username":"Jonas","devices":["iPhone 13 Pro","Samsung Galaxy S30"]}';
echo prettifyJson($s); // Pretty print the JSON string.
 
?>

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.




Reffered: https://www.geeksforgeeks.org


Algorithms

Related
Introduction to Searching Algorithms Introduction to Searching Algorithms
How to develop an Algorithm from Scratch | Develop Algorithmic Thinking How to develop an Algorithm from Scratch | Develop Algorithmic Thinking
Quadratic Assignment Problem (QAP) Quadratic Assignment Problem (QAP)
Game of Matchsticks Game of Matchsticks
Check if it is possible to construct an array with the given conditions Check if it is possible to construct an array with the given conditions

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14