Skip to content

Instantly share code, notes, and snippets.

@ikbalsingh
Created April 26, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikbalsingh/63a76c241d50ca63bef1f10ebe76af47 to your computer and use it in GitHub Desktop.
Save ikbalsingh/63a76c241d50ca63bef1f10ebe76af47 to your computer and use it in GitHub Desktop.
Pretty Prints JSON using Java.
import java.io.*;
import java.util.*;
public class JSONPetty {
public static void main(String[] args) {
String myJsObj = "['foo', {'bar':['baz',null,1.0,2]}]";
System.out.println(prettyPrint(myJsObj));
}
public static String prettyPrint(String JSON){
String result = "";
int indent = 0;
for(char c : JSON.toCharArray()){
if(c == '{' || c == '['){
result+="\n";
for(int i = 0; i<indent; i++){
result+=" ";
}
result += c;
indent++;
result+="\n";
for(int i = 0; i<indent; i++){
result+=" ";
}
}else if(c == ','){
result+=c;
result+="\n";
for(int i = 0; i<indent; i++){
result+=" ";
}
}else if(c=='}' || c==']'){
result+="\n";
indent--;
for(int i = 0; i<indent; i++){
result+=" ";
}
result+=c;
}else{
result+= c;
}
}
return result;
}
}
/*
Output :
[
'foo',
{
'bar':
[
'baz',
null,
1.0,
2
]
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment