使用ruamel.yaml添加字典条目时,如何避免自动生成id001锚点别名?
解决ruamel.yaml修改原有锚点的问题
问题出在ruamel.yaml默认会为序列(列表)类型的锚点重新生成自动命名的别名(如id001),要保留原锚点名称,只需在加载后手动指定锚点的名称即可:
修改后的代码
import ruamel.yaml yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True yaml.indent(mapping=2, sequence=4, offset=2) raw = """--- # Some config file.. # This is the main clients config clients: foobar1: name: foo Bar 1 auth: false count: 1290 barboz: name: BarraBoz auth: true count: 19 uids_default: &uids_default - attribute_email: mail datafile: vars1 uids: - <<: *uids_default skip: true - <<: *uids_default issuer: http://foo.bar """ vanhelst = {"adfs": 124423423, "123": "adsfadsfasdf", "name": "Dirk Van helst"} data = yaml.load(raw) # 手动指定原有锚点的名称,防止自动生成别名 data['uids_default'].anchor.name = 'uids_default' data["clients"].insert(len(data["clients"]), "vanhelst", vanhelst) # Write to file with open("/tmp/out.yml", "w") as f: yaml.dump(data, f)
输出的YAML文件
# Some config file.. # This is the main clients config clients: foobar1: name: foo Bar 1 auth: false count: 1290 barboz: name: BarraBoz auth: true count: 19 vanhelst: adfs: 124423423 '123': adsfadsfasdf name: Dirk Van helst uids_default: &uids_default - attribute_email: mail datafile: vars1 uids: - <<: *uids_default skip: true - <<: *uids_default issuer: http://foo.bar
原理说明
ruamel.yaml加载YAML时,会将带锚点的序列对象转为CommentedSeq类型,但其锚点名称在序列化时可能被自动重置。通过手动设置anchor.name为原锚点名称,就能强制dump时使用原有锚点标识,避免生成自动命名的别名。
内容的提问来源于stack exchange,提问作者Dick Visser
相关产品推荐
相关产品推荐

