From 5a74d6f72f250361f19d71c384ce9aa35c234985 Mon Sep 17 00:00:00 2001 From: Lushiyao5 <321342421+Lushiyao5@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:31:17 -0500 Subject: [PATCH] Raise MalformedJSON for mismatched closing tokens --- src/partial_json_parser/core/myelin.py | 12 +++++++----- tests/test_examples.py | 8 ++++++++ 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/partial_json_parser/core/myelin.py b/src/partial_json_parser/core/myelin.py index 69bcd82..5f36438 100644 --- a/src/partial_json_parser/core/myelin.py +++ b/src/partial_json_parser/core/myelin.py @@ -4,7 +4,7 @@ from typing import List, Tuple, Union from .complete import _fix -from .exceptions import PartialJSON +from .exceptions import MalformedJSON, PartialJSON from .options import * finditer = compile(r'["\[\]{}]').finditer @@ -47,11 +47,13 @@ def is_escaped(index: int): elif not in_string: if char == "}": - _i, _char = stack.pop() - assert _char == "{", f"Expected '{{' at index {_i}, got '{_char}'" + if not stack or stack[-1][1] != "{": + raise MalformedJSON(f"Unexpected token {char!r} at index {i}") + stack.pop() elif char == "]": - _i, _char = stack.pop() - assert _char == "[", f"Expected '[' at index {_i}, got '{_char}'" + if not stack or stack[-1][1] != "[": + raise MalformedJSON(f"Unexpected token {char!r} at index {i}") + stack.pop() else: stack.append((i, char)) diff --git a/tests/test_examples.py b/tests/test_examples.py index 7bf8727..2c08fa3 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -95,6 +95,14 @@ def test_error(): parse_json("--") +def test_malformed_closing_tokens(): + for json_string in ("]", "}", "[}", "{]", '{"a": 1]', "[1, 2}"): + with raises(MalformedJSON): + fix_fast(json_string) + with raises(MalformedJSON): + parse_json(json_string) + + def test_fix(): assert fix("[") == fix_fast("[") == ("[", "]") assert fix("[0.") == fix_fast("[0.") == ("[0", "]")