Skip to content

Instantly share code, notes, and snippets.

@junmakii
Created September 18, 2017 06:46
Show Gist options
  • Select an option

  • Save junmakii/7c46a5b3343bac89c9f06226f9579064 to your computer and use it in GitHub Desktop.

Select an option

Save junmakii/7c46a5b3343bac89c9f06226f9579064 to your computer and use it in GitHub Desktop.
# coding: utf-8
def encode_object_and_list(data, encoding='utf=8'):
"""
:rtype: Union[list, tuple, dict]
>>> encode_object_and_list({u"name": u"James"})
{'name': 'James'}
>>> encode_object_and_list([[u'James'], [u'John']])
[['James'], ['John']]
"""
def encode(s):
return (
s.encode(encoding)
if isinstance(s, unicode)
else s)
if isinstance(data, dict):
new_data = {}
for key, value in data.items():
if isinstance(value, (dict, list, tuple)):
new_data[encode(key)] = encode_object_and_list(value)
else:
new_data[encode(key)] = encode(value)
else:
new_data = []
for value in data:
if isinstance(value, (dict, list, tuple)):
new_data.append(encode_object_and_list(value))
else:
new_data.append(encode(value))
return new_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment