将 YAML 文件转换为 Python JSON 对象

编程入门 行业动态 更新时间:2024-10-28 13:22:39
问题描述

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

How can I load a YAML file and convert it to a Python JSON object?

我的 YAML 文件如下所示:

My YAML file looks like this:

Section: heading: Heading 1 font: name: Times New Roman size: 22 color_theme: ACCENT_2SubSection: heading: Heading 3 font: name: Times New Roman size: 15 color_theme: ACCENT_2Paragraph: font: name: Times New Roman size: 11 color_theme: ACCENT_2Table: style: MediumGrid3-Accent2

推荐答案

你可以使用PyYAMLp>

you can use PyYAML

pip install PyYAML

在 ipython 控制台中:

And in the ipython console:

In [1]: import yamlIn [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'}}
  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

将 YAML 文件转换为 Python JSON 对象

本文发布于:2023-05-22 18:52:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!