简体   繁体   English

将YAML文件转换为Python中的JSON object

[英]Converting a YAML file to JSON object in Python

How can I load a YAML file and convert it to a Python JSON object?如何加载 YAML 文件并将其转换为 Python JSON object?

My YAML file looks like this:我的 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

you can use PyYAML你可以使用PyYAML

pip install PyYAML

And in the ipython console:在 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'}}

The PyYAML library is intended for this purpose 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)

Notes: PyYAML only supports the pre-2009, YAML 1.1 specification.注意:PyYAML 仅支持 2009 之前的 YAML 1.1 规范。
ruamel.yaml is an option if YAML 1.2 is required.如果需要 YAML 1.2,则 ruamel.yaml 是一个选项。

pip install ruamel.yaml

There is no such thing as a Python JSON object.没有 Python JSON 对象这样的东西。 JSON is a language independent file format that finds its roots in JavaScript, and is supported by many languages. JSON 是一种独立于语言的文件格式,其根源在于 JavaScript,并且受到许多语言的支持。

If your YAML document adheres to the old 1.1 standard, ie pre-2009, you can use PyYAML as suggested by some of the other answers.如果您的 YAML 文档遵循旧的 1.1 标准,即 2009 之前的标准,您可以按照其他一些答案的建议使用 PyYAML。

If it uses the newer YAML 1.2 specification, which made YAML into a superset of JSON, you should use ruamel.yaml (disclaimer: I am the author of that package, which is a fork of 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)

which generates output.json :生成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 , apart from supporting YAML 1.2, has many PyYAML bugs fixed. ruamel.yaml除了支持 YAML 1.2 之外,还修复了许多 PyYAML 错误。 You should also note that PyYAML's load() is also documented to be unsafe, if you don't have full control over the input at all times.您还应该注意,如果您无法始终完全控制输入,则 PyYAML 的load()也被记录为不安全的。 PyYAML also loads scalar numbers 021 as integer 17 instead of 21 and converts scalar strings like on , yes , off to boolean values (resp. True , True and False ). PyYAML 还将标量数字021加载为整数17而不是21并将标量字符串(如onyesoff为布尔值(分别为TrueTrueFalse )。

In python3 you can use pyyaml .在 python3 中,您可以使用pyyaml

$ pip3 install pyyaml

Then you load your yaml file and dump it into json:然后加载 yaml 文件并将其转储到 json 中:

import yaml, json

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

Output:输出:

{"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"}}
import yaml
import json   

def create_json():
    with open("document.yaml","r") as yaml_doc:
        yaml_to_dict=yaml.load(yaml_doc,Loader=yaml.FullLoader)
        # write this dictionary as json object 
        with open("document.json","w") as json_doc:
            json.dump(yaml_to_dict,json_doc)
    print("yaml file is converted to json")

you need to install pip install pyyaml你需要安装pip install pyyaml

For what it's worth, here is a shell alias based on ruamel.yaml that works as a filter:值得一提的是,这是一个基于 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))'"

Usage:用法:

yaml2json < foo.yaml > foo.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM