Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin-origin/2.0' into 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
maicol07 committed Jul 9, 2022
2 parents a1a3dac + e9425b2 commit da3c0e3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
11 changes: 8 additions & 3 deletions src/masoniteorm/models/Model.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,17 @@ class JsonCast:
"""Casts a value to JSON"""

def get(self, value):
if isinstance(value, dict) or isinstance(value, list):
return value
if not isinstance(value, str):
return json.dumps(value)

return json.loads(value)
return value

def set(self, value):
if isinstance(value, str):
# make sure the string is valid JSON
json.loads(value)
return value

return json.dumps(value)


Expand Down
9 changes: 6 additions & 3 deletions tests/models/test_models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import unittest
from src.masoniteorm.models import Model
import pendulum
Expand Down Expand Up @@ -89,14 +90,15 @@ def test_model_can_cast_attributes(self):
model = ModelTest.hydrate(
{
"is_vip": 1,
"payload": '{"key": "value"}',
"payload": '["item1", "item2"]',
"x": True,
"f": "10.5",
"d": 3.14,
}
)

self.assertEqual(type(model.payload), dict)
self.assertEqual(type(model.payload), str)
self.assertEqual(type(json.loads(model.payload)), list)
self.assertEqual(type(model.x), int)
self.assertEqual(type(model.f), float)
self.assertEqual(type(model.is_vip), bool)
Expand All @@ -110,7 +112,8 @@ def test_model_can_cast_dict_attributes(self):
{"is_vip": 1, "payload": dictcasttest, "x": True, "f": "10.5"}
)

self.assertEqual(type(model.payload), dict)
self.assertEqual(type(model.payload), str)
self.assertEqual(type(json.loads(model.payload)), dict)
self.assertEqual(type(model.x), int)
self.assertEqual(type(model.f), float)
self.assertEqual(type(model.is_vip), bool)
Expand Down

0 comments on commit da3c0e3

Please sign in to comment.