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

My YAML file looks like this:

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

推荐答案

you can use PyYAML

pip install PyYAML

And in the ipython console:

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'}}

Json相关问答推荐

Swift解码错误类型与`Bool`type不一致

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

在scala中将字符串列转换为 struct 的JSON映射

如何在数组抖动中按值分组

在解码的JSON哈希中搜索数组元素

PowerShell:使用JSON原生的Short命令处理JSON?

当 JSON 字段名称有空格时,ABAP 中的 JSON 反序列化

Jolt - 如何比较 if else 条件的两个值

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

如何将复杂的 JSON 反序列化为 Rust 类型?

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

如何迭代、动态加载我的表单输入元素,然后在 React 中的表单提交上检索输入值?

如何将从嵌套 Select 返回的空值转换为空数组?

如何从 rails 中的 respond_to 方法生成 json?

未捕获的类型错误:无法读取 null 的属性props

在 JSON 编码的 HTML5 数据属性中转义/编码单引号

jQuery fullcalendar 发送自定义参数并使用 JSON 刷新日历

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

MySQL Select JSON 字段属性具有值的位置

如何从 MySQL 中检索 JSON 数据?