Skip to content

Commit

Permalink
jsonutils: encode dict keys
Browse files Browse the repository at this point in the history
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
  • Loading branch information
jd committed May 13, 2015
1 parent 50e1abc commit 986ec58
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion oslo_serialization/jsonutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__'):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_jsonutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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({}), {})

Expand Down

0 comments on commit 986ec58

Please sign in to comment.