Last active
December 11, 2015 12:49
-
-
Save yllan/4603514 to your computer and use it in GitHub Desktop.
JSON reformat
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
| def reformat(json: String) = { | |
| val tab = " " | |
| var inString = false | |
| var indentLevel = 0 | |
| var index = 0; | |
| val stringLength = json.length | |
| val formatted = new StringBuilder | |
| while (index < stringLength) { | |
| val c = json.charAt(index) | |
| if (!inString && (c == '{' || c == '[')) { | |
| indentLevel += 1 | |
| formatted.append(c).append("\n" + (tab * indentLevel)) | |
| } else if (!inString && (c == '}' || c == ']')) { | |
| indentLevel -= 1 | |
| formatted.append("\n" + (tab * indentLevel)).append(c) | |
| } else if (!inString && c == ',') { | |
| formatted.append(",\n" + (tab * indentLevel)) | |
| } else if (!inString && c == ':') { | |
| formatted.append(": ") | |
| } else if (!inString && (c == ' ' || c == '\n' || c == '\t')) { | |
| } else if (c == '"') { | |
| formatted.append(c) | |
| if (index > 0 && json.charAt(index - 1) != '\'') inString = !inString | |
| } else { | |
| formatted.append(c) | |
| } | |
| index += 1 | |
| } | |
| formatted.toString | |
| } |
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
| def reformat(json: String) = { | |
| val tab = " " | |
| @tailrec | |
| def reformatIter(newJson: StringBuilder, original: String, previousChar: Char, inString: Boolean, indentLevel: Int): String = { | |
| if (original.length == 0) newJson.toString | |
| else { | |
| val currentChar = original.head | |
| val (formatted, newInString, newIndentLevel) = currentChar match { | |
| case '{' | '[' if !inString ⇒ (currentChar + "\n" + tab * (indentLevel + 1), inString, indentLevel + 1) | |
| case '}' | ']' if !inString ⇒ ("\n" + tab * (indentLevel - 1) + currentChar, inString, indentLevel - 1) | |
| case ',' if !inString ⇒ (",\n" + tab * indentLevel, inString, indentLevel) | |
| case ':' if !inString ⇒ (": ", inString, indentLevel) | |
| case ' ' | '\n' | '\t' if !inString ⇒ ("", inString, indentLevel) | |
| case '"' ⇒ (currentChar, if (previousChar == '\'') inString else !inString, indentLevel) | |
| case c ⇒ (currentChar, inString, indentLevel) | |
| } | |
| reformatIter(newJson.append(formatted), original.tail, currentChar, newInString, newIndentLevel) | |
| } | |
| } | |
| reformatIter(new StringBuilder, json, ' ', false, 0) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment