Open In App

Algorithm for JSON Formatter without using external library

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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”: “jonas@gmail.com”}
Output:

{

“username”: “Jonas”,

“email”: “jonas@gmail.com”

}

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++




#include <iostream>
#include <string>
 
std::string prettifyJson(const std::string& s)
{
    // Indentation level.
    int indent = 0;
    // Result string.
    std::string r;
 
    // Iterate over the characters in the JSON string.
    for (char x : s) {
 
        // If we encounter a '{', we increase the
        // indentation level.
        if (x == '{') {
            indent += 2;
            r += x;
            r += '\n';
            r.append(indent, ' ');
        }
 
        // If we encounter a '[', we add newline
        // character and add [ and then increase the
        // indentation level.
        else if (x == '[') {
            r += '\n';
            r.append(indent, ' ');
            indent += 2;
            r += x;
            r += '\n';
            r.append(indent, ' ');
        }
 
        // If we encounter a '}' or ']', we decrease the
        // indentation level.
        else if (x == '}' || x == ']') {
            indent -= 2;
            r += '\n';
            r.append(indent, ' ');
            r += x;
        }
 
        // If we encounter a ',', we add a newline and
        // indent the next line.
        else if (x == ',') {
            r += x;
            r += '\n';
            r.append(indent, ' ');
        }
 
        // Otherwise, we just add the character to the
        // output string.
        else {
            r += x;
        }
    }
 
    return r;
}
 
int main()
{
    // Example
    std::string s
        = "{\"username\":\"Jonas\",\"devices\":[\"iPhone "
          "13 Pro\",\"Samsung Galaxy S30\"]}";
    std::string prettified = prettifyJson(s);
    std::cout << prettified
              << std::endl; // Pretty print the JSON string.
    return 0;
}


C




#include <stdio.h>
 
char* prettifyJson(const char* s)
{
    int indent = 0; // Indentation level.
    char* r = (char*)malloc(strlen(s) * 2 + 1);
    char* result = r; // Result string.
 
    // Iterate over the characters in the JSON string.
    for (const char* x = s; *x != '\0'; x++) {
        // If we encounter a '{', we increase the
        // indentation level.
        if (*x == '{') {
            indent += 2;
            *r++ = *x;
            *r++ = '\n';
            for (int i = 0; i < indent; i++) {
                *r++ = '*';
            }
            // If we encounter a '[', we add newline
            // character and add [ and then increase the
            // indentation level.
        }
        else if (*x == '[') {
            *r++ = '\n';
            for (int i = 0; i < indent; i++) {
                *r++ = '*';
            }
            indent += 2;
            *r++ = *x;
            *r++ = '\n';
            for (int i = 0; i < indent; i++) {
                *r++ = '*';
            }
            // If we encounter a '}' or ']', we decrease the
            // indentation level.
        }
        else if (*x == '}' || *x == ']') {
            indent -= 2;
            *r++ = '\n';
            for (int i = 0; i < indent; i++) {
                *r++ = '*';
            }
            *r++ = *x;
            // If we encounter a ',', we add a newline and
            // indent the next line.
        }
        else if (*x == ',') {
            *r++ = *x;
            *r++ = '\n';
            for (int i = 0; i < indent; i++) {
                *r++ = '*';
            }
            // Otherwise, we just add the character to the
            // output string.
        }
        else {
            *r++ = *x;
        }
    }
 
    *r = '\0';
    return result;
}
 
int main()
{
    // Example
    const char* s
        = "{\"username\":\"Jonas\",\"devices\":[\"iPhone "
          "13 Pro\",\"Samsung Galaxy S30\"]}";
    char* prettified = prettifyJson(s);
    printf("%s\n",
           prettified); // Pretty print the JSON string.
    free(prettified);
    return 0;
}


Java




public class JsonPrettifier {
 
    /**
     * Method to prettify JSON string by adding appropriate indentation.
     *
     * @param jsonInput The input JSON string to prettify.
     * @return The prettified JSON string with proper indentation.
     */
    public static String prettifyJson(String jsonInput) {
        // Indentation level.
        int indent = 0;
        // Result string.
        StringBuilder result = new StringBuilder();
 
        // Iterate over the characters in the JSON string.
        for (char x : jsonInput.toCharArray()) {
 
            // If we encounter a '{', we increase the indentation level.
            if (x == '{') {
                indent += 2;
                result.append(x);
                result.append('\n');
                result.append(" ".repeat(Math.max(0, indent)));
            }
 
            // If we encounter a '[', we add newline character, add '[', and then increase the indentation level.
            else if (x == '[') {
                result.append('\n');
                result.append(" ".repeat(Math.max(0, indent)));
                indent += 2;
                result.append(x);
                result.append('\n');
                result.append(" ".repeat(Math.max(0, indent)));
            }
 
            // If we encounter a '}' or ']', we decrease the indentation level.
            else if (x == '}' || x == ']') {
                indent -= 2;
                result.append('\n');
                result.append(" ".repeat(Math.max(0, indent)));
                result.append(x);
            }
 
            // If we encounter a ',', we add a newline and indent the next line.
            else if (x == ',') {
                result.append(x);
                result.append('\n');
                result.append(" ".repeat(Math.max(0, indent)));
            }
 
            // Otherwise, we just add the character to the output string.
            else {
                result.append(x);
            }
        }
 
        return result.toString();
    }
 
    /**
     * Main method to demonstrate JSON prettifying.
     */
    public static void main(String[] args) {
        // Example
        String jsonInput = "{\"username\":\"Jonas\",\"devices\":[\"iPhone 13 Pro\",\"Samsung Galaxy S30\"]}";
        String prettified = prettifyJson(jsonInput);
        System.out.println(prettified); // Pretty print the JSON string.
    }
}


Python




def prettifyJson(s):
    """
    Prettify a JSON string.
 
    Args:
        s (str): The JSON string to prettify.
 
    Returns:
        str: The prettified JSON string.
    """
 
    # Indentation level.
    indent = 0
 
    # Result string.
    r = ""
 
    # Iterate over the characters in the JSON string.
    for x in s:
        # If we encounter a '{', we increase the indentation level.
        if x in ['{']:
            indent += 2
            r += x + "\n" + indent * "*"
        # If we encounter a '[', we add newline character and add [ and then increase the indentation level.
        elif x in ['[']:
            r += "\n" + indent * "*"
            indent += 2
            r += x + "\n" + indent * "*"
        # If we encounter a '}' or ']', we decrease the indentation level.
        elif x in ['}', ']']:
            indent -= 2
            r += "\n" + indent * "*" + x
        # If we encounter a ',', we add a newline and indent the next line.
        elif x in [',']:
            r += x + "\n" + 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"]}'
 
# Pretty print the JSON string.
print(prettifyJson(s))


C#




using System;
 
class Program
{
    static string PrettifyJson(string s)
    {
        // Indentation level.
        int indent = 0;
        // Result string.
        string r = "";
 
        // Iterate over the characters in the JSON string.
        foreach (char x in s)
        {
            // If we encounter a '{', we increase the indentation level.
            if (x == '{')
            {
                indent += 2;
                r += x;
                r += '\n';
                r += new string(' ', indent);
            }
 
            // If we encounter a '[', we add newline character and add [ and then increase the indentation level.
            else if (x == '[')
            {
                r += '\n';
                r += new string(' ', indent);
                indent += 2;
                r += x;
                r += '\n';
                r += new string(' ', indent);
            }
 
            // If we encounter a '}' or ']', we decrease the indentation level.
            else if (x == '}' || x == ']')
            {
                indent -= 2;
                r += '\n';
                r += new string(' ', indent);
                r += x;
            }
 
            // If we encounter a ',', we add a newline and indent the next line.
            else if (x == ',')
            {
                r += x;
                r += '\n';
                r += new string(' ', indent);
            }
 
            // Otherwise, we just add the character to the output string.
            else
            {
                r += x;
            }
        }
 
        return r;
    }
 
    static void Main()
    {
        // Example
        string s = "{\"username\":\"Jonas\",\"devices\":[\"iPhone 13 Pro\",\"Samsung Galaxy S30\"]}";
        string prettified = PrettifyJson(s);
        Console.WriteLine(prettified);
    }
}


Javascript




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


PHP




<?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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads