jsonheal 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jsonheal
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Repair the broken JSON that LLMs return.
|
|
5
|
+
Author: episodely
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/episodely/jsonheal
|
|
8
|
+
Project-URL: Issues, https://github.com/episodely/jsonheal/issues
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# jsonheal
|
|
18
|
+
|
|
19
|
+
Repair the broken JSON that language models return. Pure Python, no dependencies.
|
|
20
|
+
|
|
21
|
+
Fixes: markdown code fences and chatter around the JSON, trailing commas, single quotes, unquoted keys, `None`/`True`/`False`, comments, smart quotes, and output that was cut off mid-way (open strings, arrays and objects get closed).
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from jsonheal import heal
|
|
25
|
+
|
|
26
|
+
heal("Sure! ```json\n{'name': 'Ali', tags: ['a', 'b',],}\n```")
|
|
27
|
+
# {'name': 'Ali', 'tags': ['a', 'b']}
|
|
28
|
+
|
|
29
|
+
heal('{"items": [{"id": 1}, {"id": 2')
|
|
30
|
+
# {'items': [{'id': 1}, {'id': 2}]}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
CLI:
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
cat llm_output.txt | python -m jsonheal
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Valid JSON is returned untouched. If nothing sensible can be recovered it raises `ValueError`. Truncated output is repaired structurally, so check that the data you get back is complete enough for your use.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
pip install jsonheal
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or copy `jsonheal.py` into your project, it has no dependencies.
|
|
48
|
+
|
|
49
|
+
## Test
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
python -m pytest
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
MIT licensed.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
jsonheal.py,sha256=DW_KJwRq7ACQcrAIS604TcPUz7ul8mhP5y6A3y1cYH8,4309
|
|
2
|
+
jsonheal-0.1.0.dist-info/licenses/LICENSE,sha256=MCOsqUacTi2UpUeAFoy4aKIoH4O4FwpAS7rdeIxx7EU,1066
|
|
3
|
+
jsonheal-0.1.0.dist-info/METADATA,sha256=6j5n2oXpKm_DXLFKfZc_kzKz8SYI9oeuLBywvoszAAY,1484
|
|
4
|
+
jsonheal-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
jsonheal-0.1.0.dist-info/entry_points.txt,sha256=hVdbRC8uxC7VXLMzPHE_8r_hIrXckvY17sobg-Itgbs,43
|
|
6
|
+
jsonheal-0.1.0.dist-info/top_level.txt,sha256=8njk0C2EZrYC_02nPoljyHIgeS_GpGezAI7Mqz9owKs,9
|
|
7
|
+
jsonheal-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 episodely
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jsonheal
|
jsonheal.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Repair the broken JSON that LLMs love to return."""
|
|
2
|
+
import json, re, sys, argparse
|
|
3
|
+
|
|
4
|
+
def _strip_fences(s):
|
|
5
|
+
m = re.search(r"```(?:json)?\s*(.*?)```", s, re.S)
|
|
6
|
+
if m:
|
|
7
|
+
return m.group(1)
|
|
8
|
+
return s
|
|
9
|
+
|
|
10
|
+
def _extract(s):
|
|
11
|
+
starts = [i for i in (s.find("{"), s.find("[")) if i != -1]
|
|
12
|
+
return s[min(starts):] if starts else s
|
|
13
|
+
|
|
14
|
+
def _fix_plain(segment):
|
|
15
|
+
"""Rewrites applied only to text OUTSIDE string literals."""
|
|
16
|
+
segment = re.sub(r"\bNone\b", "null", segment)
|
|
17
|
+
segment = re.sub(r"\bTrue\b", "true", segment)
|
|
18
|
+
segment = re.sub(r"\bFalse\b", "false", segment)
|
|
19
|
+
# unquoted keys
|
|
20
|
+
segment = re.sub(r"([\{,]\s*)([A-Za-z_][\w\-]*)(\s*:)", r'\1"\2"\3', segment)
|
|
21
|
+
return segment
|
|
22
|
+
|
|
23
|
+
def _normalize(s):
|
|
24
|
+
"""String-aware pass: strip comments, convert single-quoted strings and
|
|
25
|
+
fix Python literals, all without touching the inside of string values."""
|
|
26
|
+
s = (s.replace("\u201c", '"').replace("\u201d", '"')
|
|
27
|
+
.replace("\u2018", "'").replace("\u2019", "'"))
|
|
28
|
+
out, plain = [], []
|
|
29
|
+
i, n = 0, len(s)
|
|
30
|
+
|
|
31
|
+
def flush_plain():
|
|
32
|
+
if plain:
|
|
33
|
+
out.append(_fix_plain("".join(plain)))
|
|
34
|
+
plain.clear()
|
|
35
|
+
|
|
36
|
+
while i < n:
|
|
37
|
+
ch = s[i]
|
|
38
|
+
if ch == '/' and i + 1 < n and s[i + 1] == '/':
|
|
39
|
+
j = s.find('\n', i)
|
|
40
|
+
i = n if j == -1 else j
|
|
41
|
+
elif ch == '/' and i + 1 < n and s[i + 1] == '*':
|
|
42
|
+
j = s.find('*/', i + 2)
|
|
43
|
+
i = n if j == -1 else j + 2
|
|
44
|
+
elif ch == '"':
|
|
45
|
+
flush_plain()
|
|
46
|
+
j = i + 1
|
|
47
|
+
while j < n:
|
|
48
|
+
if s[j] == '\\':
|
|
49
|
+
j += 2
|
|
50
|
+
continue
|
|
51
|
+
if s[j] == '"':
|
|
52
|
+
break
|
|
53
|
+
j += 1
|
|
54
|
+
out.append(s[i:min(j + 1, n)])
|
|
55
|
+
i = j + 1
|
|
56
|
+
elif ch == "'":
|
|
57
|
+
flush_plain()
|
|
58
|
+
# a ' closes the string only when followed by a JSON delimiter;
|
|
59
|
+
# otherwise it is an apostrophe inside the value
|
|
60
|
+
j = i + 1
|
|
61
|
+
while j < n:
|
|
62
|
+
if s[j] == '\\':
|
|
63
|
+
j += 2
|
|
64
|
+
continue
|
|
65
|
+
if s[j] == "'":
|
|
66
|
+
k = j + 1
|
|
67
|
+
while k < n and s[k] in ' \t\r\n':
|
|
68
|
+
k += 1
|
|
69
|
+
if k >= n or s[k] in ':,}]':
|
|
70
|
+
break
|
|
71
|
+
j += 1
|
|
72
|
+
inner = s[i + 1:j].replace('\\\'', '\'')
|
|
73
|
+
out.append(json.dumps(inner))
|
|
74
|
+
i = j + 1
|
|
75
|
+
else:
|
|
76
|
+
plain.append(ch)
|
|
77
|
+
i += 1
|
|
78
|
+
flush_plain()
|
|
79
|
+
return "".join(out)
|
|
80
|
+
|
|
81
|
+
def _close_open(s):
|
|
82
|
+
stack, in_str, esc = [], False, False
|
|
83
|
+
for ch in s:
|
|
84
|
+
if in_str:
|
|
85
|
+
if esc: esc = False
|
|
86
|
+
elif ch == "\\": esc = True
|
|
87
|
+
elif ch == '"': in_str = False
|
|
88
|
+
else:
|
|
89
|
+
if ch == '"': in_str = True
|
|
90
|
+
elif ch in "{[": stack.append("}" if ch == "{" else "]")
|
|
91
|
+
elif ch in "}]" and stack: stack.pop()
|
|
92
|
+
if in_str:
|
|
93
|
+
s += '"'
|
|
94
|
+
s = re.sub(r",\s*$", "", s)
|
|
95
|
+
s = re.sub(r':\s*$', ': null', s)
|
|
96
|
+
return s + "".join(reversed(stack))
|
|
97
|
+
|
|
98
|
+
def heal(text: str):
|
|
99
|
+
"""Return parsed Python data from messy JSON text. Raises ValueError if hopeless."""
|
|
100
|
+
try:
|
|
101
|
+
return json.loads(text)
|
|
102
|
+
except Exception:
|
|
103
|
+
pass
|
|
104
|
+
s = _extract(_strip_fences(text)).strip()
|
|
105
|
+
s = _normalize(s)
|
|
106
|
+
s = _close_open(s)
|
|
107
|
+
s = re.sub(r",\s*([\}\]])", r"\1", s) # trailing commas
|
|
108
|
+
try:
|
|
109
|
+
return json.loads(s)
|
|
110
|
+
except Exception:
|
|
111
|
+
pass
|
|
112
|
+
# tolerate chatter after a complete JSON value: parse just the first value
|
|
113
|
+
try:
|
|
114
|
+
obj, _ = json.JSONDecoder().raw_decode(s.lstrip())
|
|
115
|
+
return obj
|
|
116
|
+
except Exception as e:
|
|
117
|
+
raise ValueError(f"could not repair JSON: {e}")
|
|
118
|
+
|
|
119
|
+
def main(argv=None):
|
|
120
|
+
p = argparse.ArgumentParser(prog="jsonheal")
|
|
121
|
+
p.add_argument("file", nargs="?")
|
|
122
|
+
a = p.parse_args(argv)
|
|
123
|
+
try:
|
|
124
|
+
text = open(a.file, encoding="utf-8").read() if a.file else sys.stdin.read()
|
|
125
|
+
except OSError as e:
|
|
126
|
+
print(f"jsonheal: {e}", file=sys.stderr)
|
|
127
|
+
return 2
|
|
128
|
+
try:
|
|
129
|
+
print(json.dumps(heal(text), indent=2, ensure_ascii=False))
|
|
130
|
+
except ValueError as e:
|
|
131
|
+
print(e, file=sys.stderr)
|
|
132
|
+
return 1
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
sys.exit(main())
|