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

许多现代工具,特别是在配置管理和基础架构即代码(IaC)领域,使用JSONYAML文件来存储配置数据。如果您需要将数据从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)。

向Python添加YAML支持

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 进行处理,设置 "indent" 可以使文件更易读 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
notepad c:\temp\python_operating-systems.json
“`

使用 PowerShell 将 YAML 转换为 JSON

PowerShell 能够修改文本文件并将对象转换为包括 JSON 在内的多种格式。由于 PowerShell 是可扩展的,你可以使用 PowerShell 来使用正确的模块将 YAML 转换为 JSON 格式。

“`plaintext
PowerShell-yaml
“`

是一个扩展 PowerShell 以支持 YAML 文件的模块,截至本文写作时的最新版本是 0.4.2。按照以下步骤安装此模块。

1. 在你的计算机上打开一个 PowerShell 会话。

2. 复制以下命令,粘贴到 PowerShell 中,然后按 Enter 键。此命令使用 Install-Module cmdlet 安装 PowerShell-yaml 模块。

Install-Module PowerShell-yaml

3. 安装模块后,两个新的 cmdlet 将作为 PowerShell-yaml 模块的一部分在 PowerShell 中可用。这两个新的 cmdlets 是:

ConvertFrom-Yaml – 将 YAML 数据转换为 哈希表 的 cmdlet。

ConvertTo-Yaml – 将哈希表对象转换为 YAML 数据的 cmdlet。

要确认这两个 cmdlet 在 PowerShell 中可用,运行以下命令在 PowerShell 中。

Get-Command -Module PowerShell-yaml

如下所示,Get-Command cmdlet 列出了来自 PowerShell-yaml 模块的 cmdlet。

Getting the PowerShell-yaml cmdlets

编写转换脚本

要创建 YAML 到 JSON 转换的 PowerShell 脚本,请按照以下说明操作。

1. 打开您的代码编辑器,在您的工作目录中创建一个名为 convert-os.ps1 的新文件。

2. 将下面的代码复制并粘贴到空白的convert-os.ps1文件中。下面的代码片段读取操作系统配置文件 operating-systems.yml,并将其转换为 JSON 格式。一旦转换为 JSON,它就会将 JSON 存储在文件PowerShell_operating-systems.json中。

#convert-os.ps1
 # 使用 Get-Content 读取 YAML 文件,并使用 ConvertFrom-Yaml 将数据转换为哈希表。$os_list 变量存储了哈希表对象。
 $os_list = (Get-Content -Path "C:\temp\operating-systems.yml" | ConvertFrom-Yaml)
 # 使用 ConvertTo-Json 将 $os_list 变量中的哈希表对象转换为 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. 运行脚本后,打开上一步中 C:\temp\PowerShell_operating-systems.json 这个转换操作系统脚本创建的 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,请参考 下载和安装 页面在你的计算机上安装它。

向 Go 添加 YAML 支持

与 PowerShell 和 Python 一样,JSON 支持是 Go 核心库的一部分,但 YAML 不是。要在 Go 中添加 YAML 支持,你需要首先使用 go get 命令安装 YAML.v3 包。要安装 YAML.v3 包:

首先,在你的计算机上,打开你想要使用的命令行 shell,比如命令提示符或 PowerShell。本示例使用 PowerShell。

接下来,在 PowerShell 中复制并运行以下命令。该命令将下载并安装包名为的包。

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

编写转换脚本

要创建 YAML 到 JSON 转换的 Go 脚本,请按照以下说明操作。

1. 打开您的代码编辑器,在您的工作目录中创建一个名为的新文件。

2. 复制下面的代码并粘贴到空白的文件中。该代码导入所需的包,定义了一些内存结构,导入了 YAML 文件,并将其转换为 JSON,然后写入一个名为的 JSON 文件。

// 这告诉go要加载哪个函数。
 package main
 // 导入包:
 import (
  // JSON 模块
     "encoding/json"
  // 用于将输出写入屏幕
     "fmt"
  // 用于读取和写入文件
     "io/ioutil"
 // YAML 模块
     "gopkg.in/yaml.v3"
 )
 // 定义两个 "Structs",这些是内存中的数据结构,并与
 // 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 提取到您的 Struct 中
     var oses operatingSystems
     yaml.Unmarshal(yamlFile, &oses)
 // 使用来自 YAML Struct 的数据创建 JSON Struct
 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. 在您的计算机上打开要使用的命令行 shell。在 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/