解決Python 2下的json.loads()導致的unicode編碼問題

python 2下使用json.loads往往會導致最終的結果編碼是unicode,並不是我們想要的str型,如下所示:

test = {"name": "扎克伯格", "age":18}
print test
test_json = json.dumps(test, ensure_ascii=False)
print test_json
test1 = json.loads(test_json)
print test1
運行的結果是:

{'age': 18, 'name': '\xe6\x89\x8e\xe5\x85\x8b\xe4\xbc\xaf\xe6\xa0\xbc'}
{"age": 18, "name": "扎克伯格"}
{u'age': 18, u'name': u'\u624e\u514b\u4f2f\u683c'}
 

由於json.loads()使用較多的場景就是在網絡請求中,網上找了很多方案都不行,最後找到一個可行的方案,那就是通過對轉換後的字典進行遍歷實現一步步的編碼就可以了。因此我們可以自己寫一個轉換函數來專門針對這個unicode編碼的問題。

轉換函數的代碼如下:

def unicode_convert(input):
    if isinstance(input, dict):
        return {unicode_convert(key): unicode_convert(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [unicode_convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input
 

然後再來測試一下效果:

test = {"name": "扎克伯格", "age":18}
print test
test_json = json.dumps(test, ensure_ascii=False)
print test_json
test1 = json.loads(test_json)
print test1
test2 = unicode_convert(json.loads(test_json))
print test2
打印的結果是:

{'age': 18, 'name': '\xe6\x89\x8e\xe5\x85\x8b\xe4\xbc\xaf\xe6\xa0\xbc'}
{"age": 18, "name": "扎克伯格"}
{u'age': 18, u'name': u'\u624e\u514b\u4f2f\u683c'}
{'age': 18, 'name': '\xe6\x89\x8e\xe5\x85\x8b\xe4\xbc\xaf\xe6\xa0\xbc'}
符合原來的預期,問題解決(因爲python控制檯打印的字典中的中文會出現unicode,這個並不影響)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章