This article describes how to parse JSON in Python and perform custom encoding at the same time. For more information about how to deserialize the file content or strings, see deserialize, due to the encoding problem of the original content, the deserialized content may need to be encoded (for example, converting unicode objects to str ).
In Python, one way is to use json. load or json. loads deserialization to obtain the dict object, and then encode the dict object.
However, in json. load and json. loads, the optional parameter object_hook exists. By using this parameter, you can directly process the deserialized dict and use the new dict to replace the original dict.
Usage:
The code is as follows:
D = json. loads (json_str, object_hook = _ decode_dict)
See _ decode_dict and _ decode_list used in Shadowsocks:
The code is as follows:
Def _ decode_list (data ):
Rv = []
For item in data:
If isinstance (item, unicode ):
Item = item. encode ('utf-8 ')
Elif isinstance (item, list ):
Item = _ decode_list (item)
Elif isinstance (item, dict ):
Item = _ decode_dict (item)
Rv. append (item)
Return rv
Def _ decode_dict (data ):
Rv = {}
For key, value in data. iteritems ():
If isinstance (key, unicode ):
Key = key. encode ('utf-8 ')
If isinstance (value, unicode ):
Value = value. encode ('utf-8 ')
Elif isinstance (value, list ):
Value = _ decode_list (value)
Elif isinstance (value, dict ):
Value = _ decode_dict (value)
Rv [key] = value
Return rv
Refer:
1. https://docs.python.org/2/library/json.html
2. https://github.com/clowwindy/shadowsocks/blob/master/shadowsocks/utils.py