Skip to main content
 首页 » 编程设计

Python 类到 Yaml/JSON

2024年09月07日9开发

<分区>

我对 YAML/JSON 不满意。

我缺少继承。

是否可以将 Python 类的层次结构导出为 YAML/JSON?

这样我就可以使用我最喜欢的具有自动完成功能的 IDE 来构建我的数据结构。

在我的例子中,结果应该被输入到 SaltStack 中。但这与配置管理完全无关,因为结果应该是纯 YAML/JSON。

我想将类导出到 yaml。永远只有类,没有实例。至少我今天是这么想的。

我认为使用这个约束是有意义的:类没有方法,除了属性。并且只获取属性,从不设置属性。

我从以下位置获取示例 json:https://www.json2yaml.com/

{ 
  "json": [ 
    "rigid", 
    "better for data interchange" 
  ], 
  "yaml": [ 
    "slim and flexible", 
    "better for configuration" 
  ], 
  "object": { 
    "key": "value", 
    "array": [ 
      { 
        "null_value": null 
      }, 
      { 
        "boolean": true 
      }, 
      { 
        "integer": 1 
      } 
    ] 
  }, 
  "paragraph": "Blank lines denote\nparagraph breaks\n", 
  "content": "Or we\ncan auto\nconvert line breaks\nto save space" 
} 

下面是上述 json 的 python 语法示例:

class json: 
    data = ['rigi', 'better for data interchange'] 
 
 
class yaml: 
    data = ['slim and flexible', 'better for configuration'] 
 
 
class object: 
    key = 'value' 
    array = [dict(null_value=None), dict(boolean=True), dict(integer=1)] 
 
 
class paragraph: 
    data = 'Blank lines denote\nparagraph breaks\n' 
 
 
class content: 
    data = '''Or we 
can auto 
convert line breaks 
to save space''' 

以上只是简单介绍了如何使用 Python 类创建数据结构。