如何将 YAML 转换为 JSON [Python、PowerShell、Go]

許多現代工具,特別是在配置管理和基礎設施即代碼(IaC)領域中,使用JSON或YAML文件來存儲配置數據。如果您需要將數據從YAML轉換為JSON格式,那麼本文就是為您而寫的。

在本文中,您將學習到多種將YAML轉換為JSON格式的方法,包括使用Python、PowerShell和Go進行腳本編寫。

先決條件

如果您希望按照本教程中的示例進行操作,請確保您擁有

  • A code editor. This article will use Visual Studio Code version 1.55.1. Feel free to use any code editor you want.
  • 要開始將YAML轉換為JSON,您需要一個示例YAML內容。將下面的內容複製到一個名為”operating-systems.yml”的新文件中。將YAML文件保存在您的工作目錄中。
operating-systems.yml
Windows 10: 100
Windows Server 2019: 50
Windows Server 2022: 1
MacOS: 3
CentOS: 75
Photon: 12

使用Python將YAML轉換為JSON

Python是一種非常適合自動化的語言。但您知道您可以擴展Python的功能並使用它來將文檔從YAML轉換為JSON嗎?您只需執行幾個步驟,很快就可以開始將YAML轉換為JSON。

這一節的示例需要您已安裝 Python 3.9PIP(截至本文寫作時的最新版本為21.0.1)。

將 YAML 支持添加到 Python

Python 沒有內置對 YAML 的支持。這意味著 Python 默認情況下無法讀取或解釋 YAML 文檔。要在 Python 中添加 YAML 支持,您首先需要安裝 PyYAML 模塊

要安裝 PyYAML 模塊,您需要運行 pip 命令,這是 Python 的包安裝程序。為此,請按照以下步驟操作。

首先,打開您喜歡的命令解釋器,例如命令提示符或 PowerShell。 pip 命令應該在其中的任何一個上運行。本例使用 PowerShell。

接下來,在 PowerShell 中運行下面的命令。此命令將安裝 PyYAML 模塊。

pip install pyyaml

如下面的截圖所示,pip 安裝了 PyYAML 的最新版本(截至本文寫作時為5.4.1)。

Installing the PyYAML module

編寫轉換腳本

現在您已經安裝了所需的模塊(PyYAML),您可以開始編寫轉換腳本。要創建 YAML 到 JSON 的 Python 腳本,請按照以下步驟操作。

1. 打開您的代碼編輯器,並在您的工作目錄中創建一個名為 convert-os.py 的新文件。該文件是您的腳本。

2. 將以下代碼複製並粘貼到您的空白convert-os.py文件中。此腳本將讀取operating-systems.yml的YAML內容,將內容轉換為JSON格式,並將JSON輸出寫入python_operating-systems.json文件。

## convert-os.py
## 導入處理JSON和YAML的模塊
import yaml
import json

## 創建變量來保存要導入的數據
os_list = {}

## 讀取YAML文件
with open("c:\temp\operating-systems.yml") as infile:
     # 將YAML轉換為上面定義的變量中的列表 os_list = yaml.load(infile, Loader=yaml.FullLoader)     # 將列表打印到控制台上 print(os_list)
 Open a file to write the JSON output. The 'w' makes the file writable
 with open("c:\temp\python_operating-systems.json", 'w') as outfile:
     # 將JSON轉換為更易讀的文件 json.dump(os_list, outfile, indent=4) print("JSON文件已寫入。")

3. 儲存convert-os.py腳本。

運行轉換腳本

創建轉換腳本後,現在是時候進行測試了。要執行YAML到JSON的Python腳本,請按照以下步驟進行:

1. 打開終端窗口。本文使用PowerShell,但命令提示符(CMD)同樣適用。

2. 複製以下命令,粘貼到 PowerShell 中,然後按 Enter 鍵。此命令運行 Python 可執行程序,以調用您在上一節中創建的 convert-os.py 腳本。

python c:\temp\convert-os.py

執行命令後,您應該會在屏幕上看到類似下面圖像的輸出。正如您所見,該命令在屏幕上顯示了 JSON 輸出並將相同的輸出保存到 c:\temp\python_operating-systems.json 文件中。

Running the YAML to JSON conversion script using Python

3. 最後,打開名為 python_operating-systems.json 的 JSON 文件,這應該是 convert-os.py Python 腳本創建的。在本例中,要在記事本中打開文件,請在 PowerShell 中運行以下命令。

notepad C:\temp\python_operating-systems.json
Viewing the python_operating-systems.json file in notepad

使用 PowerShell 將 YAML 轉換為 JSON

PowerShell 能夠修改文本文件並將對象轉換為包括 JSON 在內的多種格式。由於 PowerShell 是可擴展的,您可以使用 PowerShell 來使用正確的模塊將 YAML 轉換為 JSON 格式。

將 YAML 支持添加到 PowerShell

PowerShell 內置支持處理 JSON 內容,但不支持 YAML。幸運的是,有一個模塊擴展了 PowerShell 以支持 YAML 文件。此模塊稱為 PowerShell-yaml,截至本文寫作時的最新版本為 0.4.2。按照以下步驟安裝此模塊。

1. 在您的計算機上打開 PowerShell 會話。

2. 複製下面的命令,將其粘貼到 PowerShell 中,然後按 Enter 鍵。此命令使用 Install-Module cmdlet 來安裝 PowerShell-yaml 模塊。

Install-Module PowerShell-yaml

3. 安裝完模塊後,PowerShell 中將會有兩個新的 cmdlets 可用,這兩個新的 cmdlets 分別是:

ConvertFrom-Yaml – 將 YAML 數據轉換為 哈希表 的 cmdlet。

ConvertTo-Yaml – 將哈希表對象轉換為 YAML 數據的 cmdlet。

要確認這兩個 cmdlets 是否可在 PowerShell 中使用,請在 PowerShell 中運行下面的命令。

Get-Command -Module PowerShell-yaml

如下所示,Get-Command cmdlet 列出了來自 PowerShell-yaml 模塊的 cmdlets。

Getting the PowerShell-yaml cmdlets

編寫轉換腳本

要創建 YAML 到 JSON 轉換的 PowerShell 腳本,請按照以下步驟進行操作。

1. 打開您的代碼編輯器,在您的工作目錄中創建一個名為 convert-os.ps1 的新文件。

2. 將以下代碼複製並粘貼到空白的convert-os.ps1文件中。下面的代碼片段讀取 operating-systems.yml 文件並將其轉換為 JSON 格式。轉換為 JSON 後,將其保存在文件PowerShell_operating-systems.json中。

#convert-os.ps1
 #使用 Get-Content 讀取 YAML 文件,並使用 ConvertFrom-Yaml 將數據轉換為 hashtable。$os_list 變量存儲 hashtable 對象。
 $os_list = (Get-Content -Path "C:\temp\operating-systems.yml" | ConvertFrom-Yaml)
 #將 $os_list 變量中的 hashtable 對象轉換為 JSON 格式,使用 ConvertTo-Json。一旦轉換為 JSON,使用 Set-Content 將其保存到 C:\temp\PowerShell_operating-systems.json 文件中。
 Set-Content -Path "C:\temp\PowerShell_operating-systems.json" -Value ($os_list | ConvertTo-Json)

3. 保存convert-os.ps1文件。

運行轉換腳本

現在您已經創建了轉換腳本,下一步是運行它將 YAML 轉換為 JSON。要執行 PowerShell 轉換腳本,請按照以下步驟進行操作。

  1. 如果您尚未打開 PowerShell 窗口,請打開一個。

2. 複製以下命令,粘貼到 PowerShell 中,然後按 Enter 鍵。此命令調用您在上一節中創建的 convert-os.ps1 腳本。

c:\temp\convert-os.ps1

3. 執行腳本後,打開上一步中 convert-os.ps1 腳本創建的 JSON 輸出文件 C:\temp\PowerShell_operating-systems.json。要這樣做,請在 PowerShell 中運行以下命令以在記事本中打開 PowerShell_operating-systems.json

notepad C:\temp\PowerShell_operating-systems.json
Viewing the content of the PowerShell_operating-systems.json file

使用 Go 轉換 YAML 為 JSON

Python 和 PowerShell 都是高級語言。高級語言使編寫腳本更容易,但也減少了一點控制權。另一方面,Go 是一種低級語言,這使得導入 YAML 數據更加複雜。

本節示例將使用 Go。截至本文撰寫時的最新版本是 go1.16.3。如果您尚未安裝 Go,請參閱 下載和安裝 頁面在您的計算機上安裝它。

將 YAML 支持添加到 Go

與 PowerShell 和 Python 一樣,JSON 支持是 Go 核心庫的一部分,但 YAML 不是。要在 Go 中添加 YAML 支持,您需要首先使用 go get 命令安裝 YAML.v3 包。要安裝 YAML.v3 包:

首先,在您的計算機上,打開您想使用的命令殼,例如命令提示符或 PowerShell。此示例使用 PowerShell。

接下來,請複製以下命令並在 PowerShell 中運行。此命令將下載並安裝套件名為 `gopkg.in/yaml.v3`。

go get gopkg.in/yaml.v3
Installing the yaml.v3 package in Go

撰寫轉換腳本

要創建 YAML 到 JSON 轉換的 Go 腳本,請按照以下說明進行操作。

1. 打開你的程式碼編輯器,在你的工作目錄中創建一個名為 `convert-os.go` 的新文件。

2. 複製下面的代碼並粘貼到空白的 convert-os.go 文件中。此代碼導入所需的套件,定義一些記憶體結構,導入 YAML 文件,並將其轉換為 JSON 後寫入一個名為 `c:\temp\go_operating-systems.json` 的 JSON 文件。

// 這告訴 go 要載入哪個函數。
 package main
 // 匯入套件:
 import (
  // JSON 模組
     "encoding/json"
  // 用於將輸出寫入螢幕
     "fmt"
  // 用於讀寫檔案
     "io/ioutil"
 // YAML 模組
     "gopkg.in/yaml.v3"
 )
 // 定義兩個「結構」,這些是記憶體中的資料結構,與
 // YAML 和 JSON 檔案的形式相符。
 type operatingSystems struct {
     Windows10         int yaml:"Windows 10"
     WindowsServer2019 int yaml:"Windows Server 2019"
     WindowsServer2022 int yaml:"Windows Server 2022"
     MacOS             int yaml:"MacOS"
     CentOS            int yaml:"CentOS"
     Photon            int yaml:"Photon"
 }
 type operatingSystemsjson struct {
     Windows10         int json:"Windows 10"
     WindowsServer2019 int json:"Windows Server 2019"
     WindowsServer2022 int json:"Windows Server 2022"
     MacOS             int json:"MacOS"
     CentOS            int json:"CentOS"
     Photon            int json:"Photon"
 }
 func main() {
   // 讓使用者知道程序已經開始
     fmt.Println("Parsing YAML file")
 // 定義輸入檔案的路徑
 var fileName string = "c:\temp\operating-systems.yml"
 // 從檔案載入 YAML。Go 需要進行錯誤處理。
 yamlFile, err := ioutil.ReadFile(fileName)
     if err != nil {
         fmt.Printf("Error reading YAML file: %s\n", err)
         return
     }
 // 將 YAML 資料提取到你的結構中
     var oses operatingSystems
     yaml.Unmarshal(yamlFile, &oses)
 // 使用 YAML 結構中的資料創建 JSON 結構
 var osesjson = operatingSystemsjson{
         Windows10:         oses.Windows10,
         WindowsServer2019: oses.WindowsServer2019,
         WindowsServer2022: oses.WindowsServer2022,
         MacOS:             oses.MacOS,
         CentOS:            oses.CentOS,
         Photon:            oses.Photon,
     }
 // 創建一個以 JSON 格式輸出的字串。
 jsonOutput, err := json.Marshal(osesjson)
 // 將結果輸出到螢幕。注意 %+v 的意思是
   // 變數名稱會與資料一起印出。這就是為什麼
   // 輸出的鍵名中沒有空格的原因。
     fmt.Printf("Result: %+v\n", osesjson)
 // 寫入 JSON 檔案
 err = ioutil.WriteFile("c:\temp\Go_operating-systems.json", jsonOutput, 0644)
 }

3. 儲存convert-os.go檔案。

執行轉換腳本

執行Go腳本使用go run命令,後面跟著腳本的檔名。要執行YAML轉JSON的Go腳本,請按照以下步驟進行。

1. 在您的電腦上,打開您想使用的命令殼。在Windows上,go將在命令提示字元或PowerShell上運作。本例使用PowerShell來運行go

2. 一旦您在PowerShell中,複製下面的命令並在PowerShell中運行它。此命令將調用go run命令來運行c:\temp\convert-os.go腳本。

go run c:\temp\convert-os.go
Running Convert-os Go script.

3. 在運行腳本後,打開C:\temp\Go_operating-systems.json這是convert-os.go腳本在前一步驟中創建的輸出檔案。本例中使用記事本打開Go_operating-systems.json

Viewing the Go_operating-systems.json in notepad

結論

在本文中,您已經學會了如何使用Python、PowerShell和Go腳本將YAML數據和文件轉換為JSON。既然您已經了解了將YAML轉換為JSON的不同方式,您認為您將更多地使用哪一種方式?

Source:
https://adamtheautomator.com/yaml-to-json/