Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11"]
python-version: ["3.10", "3.11", "3.12", "3.13"]

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand All @@ -37,4 +37,4 @@ jobs:
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
python -m unittest
python -m pytest tests/
3 changes: 3 additions & 0 deletions half_json/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from half_json.core import FixResult, JSONFixer

__all__ = ["JSONFixer", "FixResult"]
38 changes: 38 additions & 0 deletions half_json/_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from __future__ import annotations


def insert_at(text: str, value: str, pos: int) -> str:
return text[:pos] + value + text[pos:]


def remove_range(text: str, start: int, end: int) -> str:
return text[:start] + text[end:]


def build_bracket_stack(text: str, end: int | None = None) -> tuple[str, ...]:
"""Return unmatched opening brackets up to position `end`."""
if end is None:
end = len(text)
stack: list[str] = []
in_string = False
escape = False
for i in range(min(end, len(text))):
ch = text[i]
if escape:
escape = False
continue
if ch == '\\' and in_string:
escape = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch in ('{', '['):
stack.append(ch)
elif ch == '}' and stack and stack[-1] == '{':
stack.pop()
elif ch == ']' and stack and stack[-1] == '[':
stack.pop()
return tuple(stack)
58 changes: 58 additions & 0 deletions half_json/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from __future__ import annotations

import argparse
import sys

from half_json.core import JSONFixer


def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
prog="jsonfixer",
description="Fix invalid / truncated JSON.",
)
parser.add_argument("infile", nargs="?", type=argparse.FileType("r"),
default=sys.stdin, help="input file (default: stdin)")
parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"),
default=sys.stdout, help="output file (default: stdout)")
parser.add_argument("--strict", dest="strict", action="store_true", default=True)
parser.add_argument("--no-strict", dest="strict", action="store_false")
parser.add_argument("--js-style", action="store_true", default=False)
parser.add_argument("--single", action="store_true", default=False,
help="treat entire input as one JSON value")
args = parser.parse_args(argv)

fixer = JSONFixer(js_style=args.js_style)
total = 0
hit = 0

if args.single:
text = args.infile.read().strip()
if text:
result = fixer.fix(text, strict=args.strict)
args.outfile.write(result.line + "\n")
else:
for line in args.infile:
line = line.strip()
if not line:
continue
total += 1
result = fixer.fix(line, strict=args.strict)
if result.success:
args.outfile.write(result.line + "\n")
if not result.origin:
hit += 1
else:
print(result, file=sys.stderr)
if total:
print(f"total is {total} and hit {hit} --> ratio:{hit * 1.0 / total}",
file=sys.stderr)


# Backward-compatible entry point (same signature as old main.py:fixjson)
def fixjson() -> None:
main()


if __name__ == "__main__":
main()
Loading