将 YAML 文件转换为 Python JSON 对象

新手上路,请多包涵

如何加载 YAML 文件并将其转换为 Python JSON 对象?

我的 YAML 文件如下所示:

 Section:
    heading: Heading 1
    font:
        name: Times New Roman
        size: 22
        color_theme: ACCENT_2

SubSection:
    heading: Heading 3
    font:
        name: Times New Roman
        size: 15
        color_theme: ACCENT_2
Paragraph:
    font:
        name: Times New Roman
        size: 11
        color_theme: ACCENT_2
Table:
    style: MediumGrid3-Accent2

原文由 ReKx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

你可以使用 PyYAML

 pip install PyYAML

在 ipython 控制台中:

 In [1]: import yaml

In [2]: document = """Section:
   ...:     heading: Heading 1
   ...:     font:
   ...:         name: Times New Roman
   ...:         size: 22
   ...:         color_theme: ACCENT_2
   ...:
   ...: SubSection:
   ...:     heading: Heading 3
   ...:     font:
   ...:         name: Times New Roman
   ...:         size: 15
   ...:         color_theme: ACCENT_2
   ...: Paragraph:
   ...:     font:
   ...:         name: Times New Roman
   ...:         size: 11
   ...:         color_theme: ACCENT_2
   ...: Table:
   ...:     style: MediumGrid3-Accent2"""
   ...:

In [3]: yaml.load(document)
Out[3]:
{'Paragraph': {'font': {'color_theme': 'ACCENT_2',
   'name': 'Times New Roman',
   'size': 11}},
 'Section': {'font': {'color_theme': 'ACCENT_2',
   'name': 'Times New Roman',
   'size': 22},
  'heading': 'Heading 1'},
 'SubSection': {'font': {'color_theme': 'ACCENT_2',
   'name': 'Times New Roman',
   'size': 15},
  'heading': 'Heading 3'},
 'Table': {'style': 'MediumGrid3-Accent2'}}

原文由 Brown Bear 发布,翻译遵循 CC BY-SA 4.0 许可协议

PyYAML 库就是为此目的而设计的

pip install pyyaml

 import yaml
import json
with open("example.yaml", 'r') as yaml_in, open("example.json", "w") as json_out:
    yaml_object = yaml.safe_load(yaml_in) # yaml_object will be a list or a dict
    json.dump(yaml_object, json_out)

注意:PyYAML 仅支持 2009 之前的 YAML 1.1 规范。

如果需要 YAML 1.2,ruamel.yaml 是一个选项。

 pip install ruamel.yaml

原文由 Vemund Kvam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题