8000 Merge pull request #340 from twilio/serialize-obj · jstacoder/twilio-python@f4d2f6a · GitHub
[go: up one dir, main page]

Skip to content

Commit f4d2f6a

Browse files
authored
Merge pull request twilio#340 from twilio/serialize-obj
Add serializer for json object parameters
2 parents 0e0e0b9 + 9c15ca2 commit f4d2f6a

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

tests/unit/base/test_serialize.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,18 @@ def test_list(self):
107107
]
108108
actual = serialize.prefixed_collapsible_map(value, 'Prefix')
109109
self.assertEqual({}, actual)
110+
111+
112+
class ObjectTestCase(unittest.TestCase):
113+
def test_object(self):
114+
actual = serialize.object({'twilio': 'rocks'})
115+
self.assertEqual('{"twilio": "rocks"}', actual)
116+
117+
def test_list(self):
118+
actual = serialize.object(['twilio', 'rocks'])
119+
self.assertEqual('["twilio", "rocks"]', actual)
120+
121+
def test_does_not_change_other_types(self):
122+
actual = serialize.object('{"attribute":"value"}')
123+
self.assertEqual('{"attribute":"value"}', actual)
124+

twilio/base/serialize.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime
2+
import json
23

34
from twilio.base import values
45

@@ -52,3 +53,13 @@ def flatten_dict(d, result={}, prv_keys=[]):
5253
return {'{}.{}'.format(prefix, k): v for k, v in flattened.items()}
5354

5455
return {}
56+
57+
58+
def object(obj):
59+
"""
60+
Return a jsonified string represenation of obj if obj is jsonifiable else
61+
return obj untouched
62+
"""
63+
if isinstance(obj, dict) or isinstance(obj, list):
64+
return json.dumps(obj)
65+
return obj

0 commit comments

Comments
 (0)
0