Skip to content

Instantly share code, notes, and snippets.

@BenjaminUrquhart
Last active February 13, 2019 22:46
Show Gist options
  • Save BenjaminUrquhart/a1c998a32c559249aff5397bc8d143a4 to your computer and use it in GitHub Desktop.
Save BenjaminUrquhart/a1c998a32c559249aff5397bc8d143a4 to your computer and use it in GitHub Desktop.
JSON parser for r/badcode
import java.util.HashMap;
import java.util.Arrays;
public class BadJSON {
public static HashMap<String, Object> parseJSON(String s) {
String toParse = new String();
for(char character : s.toCharArray()) toParse = toParse + (character == 10 ? new String() : new String(new char[]{character}));
HashMap<String, Object> out = new HashMap<String, Object>();
if(toParse.charAt(0) != '{' || toParse.charAt(toParse.length() - 1) != '}') return out;
String tmp = new String();
String tmp2 = new String();
boolean add = false;
boolean array = false;
boolean parsing = false;
for(char c : toParse.toCharArray()){
if(c == '['){
array = true;
}
if(c == ']'){
array = false;
}
add = (c == '"' ? !add : add);
parsing = (c == ':' ? true : (c == ',' ? false : (c == '}' ? false : parsing))) || array;
if(add == true && parsing == false){
tmp = tmp + new String(new char[]{c});
}
else if(parsing == true && c != ':'){
tmp2 = tmp2 + new String(new char[]{c});
}
if((c == ',' || c == '}') && array == false){
if(tmp2.length() == 0) continue;
Object object;
tmp2 = tmp2.substring(tmp2.charAt(0) == '"' ? 1 : 0, tmp2.length() - (tmp2.charAt(tmp2.length() - 1) == '"' ? 1 : 0));
if(tmp2.charAt(0) == '{' && tmp2.charAt(tmp2.length() - 1) == '}') object = parseJSON(tmp2);
object = tmp2.charAt(0) == '"' ? tmp2.substring(1) : tmp2.equals("null") ? null : tmp2.equals("true") ? true : tmp2.equals("false") ? false : tmp2.matches("(\\d+)") && !tmp2.contains(".") ? Long.parseLong(tmp2) : tmp2;
object = !(object == null) && object.toString().charAt(0) == '[' && object.toString().charAt(object.toString().length() - 1) == ']' ?Arrays.stream(object.toString().substring(1, object.toString().length() -1).split(",")).map((obj) -> obj.equals("null") ? null : obj.equals("true") ? true : obj.equals("false") ? false : obj.matches("(\\d+)") && !obj.toString().contains(".") ? Long.parseLong(obj) : obj).toArray() : object;
out.put(tmp.substring(1), object);
tmp = new String();
tmp2 = new String();
}
}
return out;
}
public static void main(String[] args){
HashMap<String, Object> map = parseJSON("{\"test1\":\"yeet\",\"test2\":[0,true,\"2\"],\"test3\":1,\"test4\":null,\"test5\":{\"test6\":1}}");
map.forEach((x,y) -> System.out.printf("%s: [%s] %s\n", x, y == null ? "Null Pointer" : y.getClass(), y != null && y.getClass().toString().contains("[Ljava.lang.Object;") ? Arrays.toString((Object[])y) : y));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment