Json parser
clean_json_string(json_str)
Clean a JSON-like string so that it can be parsed by the built-in json module.
- Remove single-line (//...) and multi-line (/.../) comments outside of string literals.
- Convert single-quoted string literals to double-quoted ones, preserving internal apostrophes.
- Replace Python-specific boolean/null literals (True, False, None) with their JSON equivalents (true, false, null).
- Remove trailing commas in objects and arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_str |
str
|
The raw JSON-like string to clean. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A cleaned JSON string suitable for json.loads. |
Source code in dynamiq/utils/json_parser.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
extract_json_string(s)
Extract the first JSON object or array from the string by balancing brackets. The function looks for '{' or '[' and keeps track of nested brackets until they are balanced, returning the substring that contains the complete JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s |
str
|
The input string potentially containing a JSON object or array. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The extracted JSON string if found and balanced, otherwise None. |
Source code in dynamiq/utils/json_parser.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
parse_llm_json_output(response)
Attempt to parse the received LLM output into a JSON object or array. If direct parsing fails, looks for the first balanced JSON substring, then tries corrections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response |
str
|
The raw output from the LLM. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | list[Any]
|
A Python dict or list representing the parsed JSON. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the output cannot be parsed into valid JSON. |
Source code in dynamiq/utils/json_parser.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
single_quoted_replacer(match)
A helper function for clean_json_string to replace single-quoted JSON-like string literals with double-quoted equivalents, preserving internal apostrophes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
match |
Match[str]
|
The regular expression match object for a single-quoted string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The corresponding double-quoted string literal. |
Source code in dynamiq/utils/json_parser.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |