没有像 Python JSON 对象这样的东西。 JSON 是一种独立于语言的文件格式,其根源在于 JavaScript,并受到多种语言的支持。
如果您的 YAML 文档遵循旧的 1.1 标准,即 2009 年之前的标准,您可以按照其他一些答案的建议使用 PyYAML。
如果它使用更新的 YAML 1.2 规范,这使 YAML 成为 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"
}
}
ruamel.yaml 除了支持 YAML 1.2 之外,还修复了许多 PyYAML 错误。您还应该注意,如果您始终无法完全控制输入,那么 PyYAML 的 load() 也被记录为不安全的。 PyYAML 还将标量数 021 加载为整数 17 而不是 21 和 converts scalar strings like on, yes, off to boolean 值(分别为 True、True 和 False)。