From 986ec5832e233d0c78ea7065ba482b87de0d6ca7 Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Mon, 23 Mar 2015 16:03:26 +0100 Subject: [PATCH] jsonutils: encode dict keys Currently, only the dict value are converted with to_primitive(). There's no reason not to do it on keys too to support special types. Change-Id: I5b447f2fcd814088483f67e54261131cfc87ae79 --- oslo_serialization/jsonutils.py | 3 ++- tests/test_jsonutils.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/oslo_serialization/jsonutils.py b/oslo_serialization/jsonutils.py index 2702ee4..f24adbe 100644 --- a/oslo_serialization/jsonutils.py +++ b/oslo_serialization/jsonutils.py @@ -148,7 +148,8 @@ def to_primitive(value, convert_instances=False, convert_datetime=True, level=level, max_depth=max_depth) if isinstance(value, dict): - return dict((k, recursive(v)) for k, v in six.iteritems(value)) + return dict((recursive(k), recursive(v)) + for k, v in six.iteritems(value)) elif hasattr(value, 'iteritems'): return recursive(dict(value.iteritems()), level=level + 1) elif hasattr(value, '__iter__'): diff --git a/tests/test_jsonutils.py b/tests/test_jsonutils.py index e9567df..a150b43 100644 --- a/tests/test_jsonutils.py +++ b/tests/test_jsonutils.py @@ -140,6 +140,18 @@ def test_dict(self): self.assertEqual(jsonutils.to_primitive(dict(a=1, b=2, c=3)), dict(a=1, b=2, c=3)) + def test_dict_values(self): + self.assertEqual( + jsonutils.to_primitive( + dict(a=uuid.UUID("DD9FB2B6-CE81-4A7B-8B56-90E35D650A0B"))), + dict(a=u"dd9fb2b6-ce81-4a7b-8b56-90e35d650a0b")) + + def test_dict_keys(self): + self.assertEqual( + jsonutils.to_primitive( + {uuid.UUID("DD9FB2B6-CE81-4A7B-8B56-90E35D650A0B"): 4}), + {u"dd9fb2b6-ce81-4a7b-8b56-90e35d650a0b": 4}) + def test_empty_dict(self): self.assertEqual(jsonutils.to_primitive({}), {})