簡體   English   中英

將YAML文件轉換為Python中的JSON object

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

如何加載 YAML 文件並將其轉換為 Python JSON object?

我的 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

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

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

沒有 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並將標量字符串(如onyesoff為布爾值(分別為TrueTrueFalse )。

在 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"}}
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")

你需要安裝pip install pyyaml

值得一提的是,這是一個基於 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM