Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix jsanitize when recursive_msonable=True #727

Closed
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: 7 additions & 1 deletion monty/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,13 @@ def jsanitize(
pass

if recursive_msonable and isinstance(obj, MSONable):
return obj.as_dict()
return jsanitize(
obj.as_dict(),
strict=strict,
allow_bson=allow_bson,
enum_values=enum_values,
recursive_msonable=recursive_msonable,
)

if not strict:
return str(obj)
Expand Down
14 changes: 13 additions & 1 deletion tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

from monty.json import MontyDecoder, MontyEncoder, MSONable, _load_redirect, jsanitize

from . import __version__ as tests_version
from monty import __version__ as tests_version

test_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_files")

Expand Down Expand Up @@ -576,6 +576,18 @@ def test_jsanitize(self):
assert clean_recursive_msonable["hello"]["a"] == 1
assert clean_recursive_msonable["hello"]["b"] == 2

DoubleGoodMSONClass = GoodMSONClass(1, 2, 3)
DoubleGoodMSONClass.values = [GoodMSONClass(1, 2, 3)]
clean_recursive_msonable = jsanitize(
DoubleGoodMSONClass, recursive_msonable=True
)
assert clean_recursive_msonable["a"] == 1
assert clean_recursive_msonable["b"] == 2
assert clean_recursive_msonable["c"] == 3
assert clean_recursive_msonable["values"][0]["a"] == 1
assert clean_recursive_msonable["values"][0]["b"] == 2
assert clean_recursive_msonable["values"][0]["c"] == 3

d = {"dt": datetime.datetime.now()}
clean = jsanitize(d)
assert isinstance(clean["dt"], str)
Expand Down