Skip to content

Commit cdc4327

Browse files
committed
fix: Fix issue with formatting malformed jsons
1 parent d22e3db commit cdc4327

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/main/java/dev/dochia/cli/core/util/SimpleJsonFormatter.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ private static String formatJsonString(String jsonStr) {
5555

5656
case '}', ']':
5757
if (prevChar != '{' && prevChar != '[' && prevChar != '\n') {
58-
formatted.append('\n').append(indent.repeat(indentLevel - 1));
58+
formatted.append('\n').append(indent.repeat(Math.max(0, indentLevel - 1)));
5959
}
6060
indentLevel--;
6161
formatted.append(currentChar);

src/test/java/dev/dochia/cli/core/util/SimpleJsonFormatterTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,27 @@ void shouldHandleEscapedQuotesInJsonString() {
4444
String result = SimpleJsonFormatter.formatJson(input);
4545
assertThat(result).isEqualTo(expected);
4646
}
47+
48+
@Test
49+
void shouldHandleMalformedJsonWithExtraClosingBrackets() {
50+
String input = "{\"key\":\"value\"}}";
51+
String result = SimpleJsonFormatter.formatJson(input);
52+
assertThat(result).isNotNull();
53+
}
54+
55+
@Test
56+
void shouldHandleMalformedJsonWithExtraClosingSquareBrackets() {
57+
String input = "[1,2,3]]";
58+
String result = SimpleJsonFormatter.formatJson(input);
59+
assertThat(result).isNotNull();
60+
}
61+
62+
@Test
63+
void shouldHandleNestedStructures() {
64+
String input = "{\"outer\":{\"inner\":{\"deep\":\"value\"}}}";
65+
String result = SimpleJsonFormatter.formatJson(input);
66+
assertThat(result).contains("\"outer\":");
67+
assertThat(result).contains("\"inner\":");
68+
assertThat(result).contains("\"deep\": \"value\"");
69+
}
4770
}

0 commit comments

Comments
 (0)