Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add currency information to JSON

oldPadavan4007f214e81d
diff --git a/saleor/core/utils/json_serializer.py b/saleor/core/utils/json_serializer.py
index 9be9be54db..4dda883bc5 100644
--- a/saleor/core/utils/json_serializer.py
+++ b/saleor/core/utils/json_serializer.py
@@ -1,9 +1,16 @@
+import json
+
+from django.core.serializers.base import DeserializationError
from django.core.serializers.json import (
- Deserializer as JsonDeserializer, DjangoJSONEncoder,
+ DjangoJSONEncoder,
+ PythonDeserializer,
Serializer as JsonSerializer)
from prices import Money
+MONEY_TYPE = 'Money'
+
+
class Serializer(JsonSerializer):
def _init_options(self):
super()._init_options()
@@ -13,8 +20,28 @@ class Serializer(JsonSerializer):
class CustomJsonEncoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Money):
- return obj.amount
+ return {
+ '_type': MONEY_TYPE, 'amount': obj.amount,
+ 'currency': obj.currency}
return super().default(obj)
-Deserializer = JsonDeserializer
+def object_hook(obj):
+ if '_type' in obj and obj['_type'] == MONEY_TYPE:
+ return Money(obj['amount'], obj['currency'])
+ return obj
+
+
+def Deserializer(stream_or_string, **options):
+ """Deserialize a stream or string of JSON data."""
+ if not isinstance(stream_or_string, (bytes, str)):
+ stream_or_string = stream_or_string.read()
+ if isinstance(stream_or_string, bytes):
+ stream_or_string = stream_or_string.decode()
+ try:
+ objects = json.loads(stream_or_string, object_hook=object_hook)
+ yield from PythonDeserializer(objects, **options)
+ except (GeneratorExit, DeserializationError):
+ raise
+ except Exception as exc:
+ raise DeserializationError() from exc
diff --git a/tests/test_product.py b/tests/test_product.py
index e1d313a625..f24d56a26f 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -597,7 +597,8 @@ def test_product_json_serialization(product):
product.save()
data = json.loads(serializers.serialize(
"json", models.Product.objects.all()))
- assert data[0]['fields']['price'] == '10.00'
+ assert data[0]['fields']['price'] == {
+ '_type': 'Money', 'amount': '10.00', 'currency': 'USD'}
def test_product_json_deserialization(category, product_type):
@@ -612,7 +613,7 @@ def test_product_json_deserialization(category, product_type):
"name": "Kelly-Clark",
"description": "Future almost cup national",
"category": {category_pk},
- "price": "35.98",
+ "price": {{"_type": "Money", "amount": "35.98", "currency": "USD"}},
"available_on": null,
"is_published": true,
"attributes": "{{\\"9\\": \\"24\\", \\"10\\": \\"26\\"}}",