Created
September 18, 2017 06:46
-
-
Save junmakii/7c46a5b3343bac89c9f06226f9579064 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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