在Python中将YAML文件转换为JSON对象

dvtswwa3  于 2023-01-10  发布在  Python
关注(0)|答案(5)|浏览(199)

如何加载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
ovfsdjhp

ovfsdjhp1#

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
5ktev3wc

5ktev3wc2#

您可以使用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'}}
abithluo

abithluo3#

没有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加载,而不是21converts scalar strings like on , yes , off to boolean值加载(分别为TrueTrueFalse)。

bvn4nwqk

bvn4nwqk4#

在python3中,你可以使用pyyaml

$ pip3 install pyyaml

然后加载yaml文件并将其转储到json中:

import yaml, json

with open('./file.yaml') as f:
    print(json.dumps(yaml.load(f)))

输出:

{"Section": null, "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"}}
gkn4icbw

gkn4icbw5#

不管怎样,下面是一个基于ruamel.yaml的shell别名,它可以充当过滤器:

pip3 install ruamel.yaml
alias yaml2json="python3 -c 'import json, sys, ruamel.yaml as Y; print(json.dumps(Y.YAML(typ=\"safe\").load(sys.stdin), indent=2))'"

用法:

yaml2json < foo.yaml > foo.json

相关问题