Created
April 26, 2019 15:51
-
-
Save ikbalsingh/63a76c241d50ca63bef1f10ebe76af47 to your computer and use it in GitHub Desktop.
Pretty Prints JSON using Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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