Skip to content

Commit 92931e1

Browse files
committed
Refactor
1 parent 1f9879c commit 92931e1

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
# LLM JSON auto repair
22

33
A tiny library to repair JSON string output from LLM. It fixes most of the common issues from the LLM JSON output, eg:
4+
45
* Remove the ```json``` code block
56
* Add missing commas
6-
* Add missing double quotes
7+
* Add missing double quotes when possible
8+
* Replace single quotes with double quotes
79
* Escape special characters \t \n
810

911
## Usage
@@ -20,4 +22,6 @@ A tiny library to repair JSON string output from LLM. It fixes most of the commo
2022
```
2123
""";
2224
String fixedJSON = jsonAutoRepairer.repair(originalJSON);
23-
```
25+
```
26+
27+
It will automatically fix the JSON string and return the fixed JSON string if possible. In case, the JSON string cannot be fixed, it returns null

src/test/java/com/cdpn/jsonautorepair/JSONAutoRepairerTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ public void repair_should_cleanup_markdown_code_block_when_string_contain_json_c
3737

3838
}
3939

40+
41+
4042
@Test
4143
public void repair_should_return_original_string_when_the_string_is_a_valid_JSON() {
4244
String originalJSON = """
@@ -68,6 +70,7 @@ public void repair_should_not_wrap_string_in_brackets_when_the_string_is_a_JSON_
6870
assertEquals("[\"sea\",\"fish\"]", jsonAutoRepairer.repair("[\"sea\",\"fish\"]"));
6971
}
7072

73+
7174
@Test
7275
public void repair_should_add_quotes_around_unquoted_keys() {
7376
assertEquals("{\"name\":\"Alice\",\"age\":30}",
@@ -76,6 +79,23 @@ public void repair_should_add_quotes_around_unquoted_keys() {
7679
jsonAutoRepairer.repair("{name: \"Alice\", age: 30 }"));
7780
}
7881

82+
@Test
83+
public void repair_should_replace_single_quote_by_double_quote_around_key_and_value() {
84+
assertEquals("{\"name\":\"Alice\"}",
85+
jsonAutoRepairer.repair("{ 'name': 'Alice' }"));
86+
}
87+
88+
@Test
89+
public void repair_should_add_quote_to_key_and_value_when_possible() {
90+
assertEquals("{\"name\":\"Alice\"}",
91+
jsonAutoRepairer.repair("{ \"name\": Alice }"));
92+
93+
assertEquals("{\"name\":\"Alice\",\"sex\":\"female\"}",
94+
jsonAutoRepairer.repair("{ \"name\": Alice, sex: female }"));
95+
96+
}
97+
98+
7999
@Test
80100
public void repair_should_escape_internal_quote() {
81101
String originalJSON = """

0 commit comments

Comments
 (0)