Python yaml

来自百合仙子's Wiki
跳转到导航 跳转到搜索

示例

import yaml
try:
  from yaml import CLoader as Loader
  from yaml import CDumper as Dumper
except ImportError:
  from yaml import Loader, Dumper

def load(stream):
  return yaml.load(stream, Loader=Loader)

def dump(data, stream=None):
  # 转成 YAML 字符串,默认会转义 Unicode 字符
  return yaml.dump(data, stream=stream, Dumper=Dumper, allow_unicode=True)

用法

Dumper 参数

allow_unicode
是否允许Unicode字符。默认会使用 \uxxxx 转义
default_flow_style
尽量使用单行排版,否则全部使用块状排版。默认是。

给 Dumper 添加 Representer 方法

Python 2 中非 ASCII 字符串导出会添加 !!python/str tag。可使用如下方式覆盖此方法:

def represent_str(self, data):
  data = unicode(data, 'utf-8')
  tag = u'tag:yaml.org,2002:str'
  return self.represent_scalar(tag, data)
Dumper.add_representer(str, represent_str)

默认字典输出时是按键排序的。可以使用类似的方法覆盖其行为[1]

def represent_name_first_dict(self, data):
  value = []
  if 'name' in data:
    node_key = self.represent_data('name')
    node_value = self.represent_data(data['name'])
    value.append((node_key, node_value))

  for k, v in data.items():
    if k == 'name':
      continue
    node_key = self.represent_data(k)
    node_value = self.represent_data(v)
    value.append((node_key, node_value))

  return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value)

Dumper.add_representer(dict, represent_name_first_dict)

注意事项

默认不使用 C 模块(而使用纯 Python 实现),使用示例中的方法来率先尝试 C 实现。

参见

外部链接

参考资料