Skip to content
Open
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
12 changes: 7 additions & 5 deletions src/partial_json_parser/core/myelin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))

Expand Down
8 changes: 8 additions & 0 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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", "]")
Expand Down