如何從JSON獲得字符串對象而不是Unicode?我在用Python 2來解析JSONASCII編碼文本文件。當加載這些文件時json或simplejson,我的所有字符串值都轉換為Unicode對象,而不是String對象。問題是,我必須對一些只接受字符串對象的庫使用數據。我不能改變圖書館也不更新他們。是否有可能獲得字符串對象而不是Unicode對象?例>>> import json>>> original_list = ['a', 'b']>>> json_list = json.dumps(original_list)>>> json_list'["a", "b"]'
>>> new_list = json.loads(json_list)>>> new_list[u'a', u'b'] # I want these to be of type `str`, not `unicode`更新有人問了這個問題很久以前當我被困在Python 2..今天,一個簡單而干凈的解決方案是使用Python的最新版本-即Python 3向前看。
3 回答

MM們
TA貢獻1886條經驗 獲得超2個贊
def byteify(input): if isinstance(input, dict): return {byteify(key): byteify(value) for key, value in input.iteritems()} elif isinstance(input, list): return [byteify(element) for element in input] elif isinstance(input, unicode): return input.encode('utf-8') else: return input
json.load
json.loads
若要支持Python2.6或更高版本,請替換 return {byteify(key): byteify(value) for key, value in input.iteritems()}
帶著 return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()])
,因為字典理解直到Python2.7才被支持。 由于這個答案在整個解碼對象中反復出現,它具有一些不受歡迎的性能特征,可以通過非常小心地使用 object_hook
或 object_pairs_hook
參數。 到目前為止,是唯一一個能夠正確完成這一任務的人,盡管結果是,它比我的方法要復雜得多。
添加回答
舉報
0/150
提交
取消