Python中解析JSON并同時(shí)進(jìn)行自定義編碼處理實(shí)例
在對(duì)文件內(nèi)容或字符串進(jìn)行JSON反序列化(deserialize)時(shí),由于原始內(nèi)容編碼問(wèn)題,可能需要對(duì)反序列化后的內(nèi)容進(jìn)行編碼處理(如將unicode對(duì)象轉(zhuǎn)換為str)。
在Python中,一種方式是先使用json.load或json.loads反序列化得到dict對(duì)象,然后對(duì)這個(gè)dict對(duì)象進(jìn)行編碼處理。
但其實(shí)在json.load與json.loads中,有可選參數(shù)object_hook。通過(guò)使用此參數(shù),可以對(duì)反序列化得到的dict直接進(jìn)行處理,并使用處理后新的dict替代原dict返回。
使用方法為:
d = json.loads(json_str, object_hook=_decode_dict)
附Shadowsocks中使用的_decode_dict與_decode_list:
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
參考:
1.https://docs.python.org/2/library/json.html
2.https://github.com/clowwindy/shadowsocks/blob/master/shadowsocks/utils.py
相關(guān)文章
python實(shí)現(xiàn)識(shí)別手寫(xiě)數(shù)字 python圖像識(shí)別算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)識(shí)別手寫(xiě)數(shù)字,python圖像識(shí)別算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01詳解如何用django實(shí)現(xiàn)redirect的幾種方法總結(jié)
這篇文章主要介紹了如何用django實(shí)現(xiàn)redirect的幾種方法總結(jié),詳細(xì)的介紹3種實(shí)現(xiàn)方式,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11Python2.7簡(jiǎn)單連接與操作MySQL的方法
這篇文章主要介紹了Python2.7簡(jiǎn)單連接與操作MySQL的方法,涉及Python使用MySQLdb模塊操作MySQL連接及命令運(yùn)行的相關(guān)技巧,需要的朋友可以參考下2016-04-04windows下 兼容Python2和Python3的解決方法
這篇文章主要介紹了windows下 兼容Python2和Python3的解決方法,需要的朋友可以參考下2018-12-12numpy 實(shí)現(xiàn)返回指定行的指定元素的位置索引
這篇文章主要介紹了numpy 實(shí)現(xiàn)返回指定行的指定元素的位置索引操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05