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: 9 additions & 3 deletions frontmatter/default_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,15 @@ class JSONHandler(BaseHandler):
END_DELIMITER = ""

def split(self, text: str) -> tuple[str, str]:
assert self.FM_BOUNDARY is not None
_, fm, content = self.FM_BOUNDARY.split(text, 2)
return "{" + fm + "}", content
try:
_, end = json.JSONDecoder().raw_decode(text)
except json.JSONDecodeError:
# Preserve existing malformed-frontmatter behavior: load() raises
# for invalid JSON with delimiters; missing boundaries stay content.
assert self.FM_BOUNDARY is not None
_, fm, content = self.FM_BOUNDARY.split(text, 2)
return "{" + fm + "}", content
return text[:end], text[end:]

def load(self, fm: str, **kwargs: object) -> Any:
return json.loads(fm, **kwargs) # type: ignore[arg-type]
Expand Down
24 changes: 24 additions & 0 deletions tests/test_nested_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import json

import pytest

import frontmatter
from frontmatter.default_handlers import JSONHandler


@pytest.mark.parametrize('metadata', [
{'outer': {'inner': 1}, 'title': 'Example'},
{'items': [{'title': 'first'}, {'title': 'second'}]},
{'quoted': '} and {', 'nested': {'text': 'escaped " quote'}},
])
def test_nested_unindented_json_round_trip(metadata):
post = frontmatter.Post('Body\n\n{content stays content}', JSONHandler(), **metadata)
text = frontmatter.dumps(post, indent=0)
restored = frontmatter.loads(text)
assert restored.metadata == metadata
assert restored.content == post.content


def test_malformed_delimited_json_still_raises():
with pytest.raises(json.JSONDecodeError):
frontmatter.loads('{\n"title": invalid\n}\n\nBody')