如何加载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
发布于 2018-06-14 05:27:11
您可以使用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'}}
发布于 2018-06-14 05:29:12
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年前的YAML1.1规范。
如果需要YAML1.2,则ruamel.yaml是一个选项。
pip install ruamel.yaml
发布于 2018-06-14 15:15:49
没有Python JSON对象这样的东西。JSON是一种独立于语言的文件格式,它起源于JavaScript,许多语言都支持它。
如果您的YAML文档遵循旧的1.1标准,也就是2009年之前的版本,那么您可以按照一些其他答案的建议使用PyYAML。
如果它使用较新的YAML1.2规范,该规范使YAML1.2成为JSON的超集,那么您应该使用ruamel.yaml
(免责声明:我是该包的作者,这是PyYAML的一个分支)。
import ruamel.yaml
import json
in_file = 'input.yaml'
out_file = 'output.json'
yaml = ruamel.yaml.YAML(typ='safe')
with open(in_file) as fpi:
data = yaml.load(fpi)
with open(out_file, 'w') as fpo:
json.dump(data, fpo, indent=2)
它会生成output.json
{
"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"
}
}
除了支持YAML1.2之外,ruamel.yaml
还修复了许多PyYAML错误。您还应该注意到,如果您不能始终完全控制输入,PyYAML的load()
也被证明是不安全的。PyYAML还将标量数021
加载为整数17
,而不是21
和converts scalar strings like on
, yes
, off
to boolean值(分别为True
、True
和False
)。
https://stackoverflow.com/questions/50846431
复制相似问题