将对象转储到不带引号的 yaml 中 [英] Dump object into yaml without quotes

查看:42
本文介绍了将对象转储到不带引号的 yaml 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些对象想变成 yaml,唯一的问题是我需要能够将!任何东西"放入 yaml 中.没有引号.

I had some object that I want to turn into yaml, the only thing is that I need to be able to put "!anything" without quotes into it.

当我使用 pyyaml 进行尝试时,我的 yaml 文件中最终会出现 '!anything'.

When I try it with pyyaml I end up with '!anything' inside my yaml file.

我已经尝试过使用 ruamel.yaml PreservedScalarString 和 LiteralScalarString.它有点工作,但不是我需要的工作方式.问题是我最终得到了如下所示的 yaml:

I've already tried using ruamel.yaml PreservedScalarString and LiteralScalarString. And it kind of works, but not in the way that I need to work. The thing is I end up with yaml that looks like this:

10.1.1.16:
            text: '1470814.27'
            confidence: |-
              !anything

但我不需要这个 |- 符号.

But I don't need this |- symbol.

我的目标是像这样获得 yaml:

My goal is to get yaml like this:

10.1.1.16:
            text: '1470814.27'
            confidence: !anything

有什么想法可以实现吗?

Any ideas how I can achieve that?

推荐答案

要转储自定义标记,您需要定义一个类型并为该类型注册一个代表.以下是对标量执行此操作的方法:

To dump a custom tag, you need to define a type and register a representer for that type. Here's how to do it for scalars:

import yaml

class MyTag:
  def __init__(self, content):
    self.content = content

  def __repr__(self):
    return self.content

  def __str__(self):
    return self.content

def mytag_dumper(dumper, data):
  return dumper.represent_scalar("!anything", data.content)

yaml.add_representer(MyTag, mytag_dumper)

print(yaml.dump({"10.1.1.16": {
    "text": "1470814.27",
    "confidence": MyTag("")}}))

这个发射

10.1.1.16:
  confidence: !anything ''
  text: '1470814.27'

注意标签后面的'',它是带标签的标量(不,你不能去掉它).您也可以标记集合,但您需要相应地使用 represent_sequencerepresent_mapping.

Note the '' behind the tag, which is the tagged scalar (no, you can't get rid of it). You can tag collections as well but you'll need to use represent_sequence or represent_mapping accordingly.

这篇关于将对象转储到不带引号的 yaml 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆