我正在使用pyyaml(版本:5.1)和Python 2來解析傳入 POST API 請求的YAML數(shù)據(jù)正文。傳入請求的正文包含一些 Unicode 對象以及一些字符串對象。鏈接中給出的解決方案用于將 YAML 映射加載到 OrderedDict 中,其中流引用傳入的 POST API 請求的YAML數(shù)據(jù)正文。但是,我必須使用從某些僅接受字符串對象的庫的鏈接生成的 OrderedDict 。我無法更改庫也無法更新它,我必須使用 Python 2。目前正在使用的解決方案是,獲取從鏈接生成的 OrderedDict遞歸地解析它,將任何找到的 Unicode 對象轉(zhuǎn)換為 String 對象其示例代碼如下,def convert(data): if isinstance(data, unicode): return data.encode('utf-8') if isinstance(data, list): return [convert(item) for item in data] if isinstance(data, dict): newData = {} for key, value in data.iteritems(): newData[convert(key)] = convert(value) return newData return data盡管這可行,但該解決方案效率不高,因為完整的 OrderedDict 在創(chuàng)建后才被解析。有沒有一種方法可以在 OrderedDict 生成之前或期間完成數(shù)據(jù)轉(zhuǎn)換,以避免再次解析它?
1 回答

PIPIONE
TA貢獻1829條經(jīng)驗 獲得超9個贊
您可以提供一個自定義構(gòu)造函數(shù),該構(gòu)造函數(shù)始終將 YAML!!str標量加載到 Python unicode 字符串:
import yaml
from yaml.resolver import BaseResolver
def unicode_constructor(self, node):
# this will always return a unicode string;
# the default loader would convert it to ASCII-encoded str if possible.
return self.construct_scalar(node)
yaml.add_constructor(BaseResolver.DEFAULT_SCALAR_TAG, unicode_constructor)
之后,yaml.load將始終返回 unicode 字符串。
(代碼未經(jīng)測試,因為我沒有安裝 Python 2)
添加回答
舉報
0/150
提交
取消