当前位置:网站首页 > 更多 > 玩电脑 > 正文

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

作者:精品下载站 日期:2024-12-14 13:07:24 浏览:12 分类:玩电脑

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


许多现代工具,特别是在配置管理和基础设施即代码 (IaC) 空间中,使用 JSON 或 YAML 文件来存储配置数据。如果您需要将数据从 YAML 转换为 JSON 格式,那么本文适合您。

在本文中,您将学习将数据 YAML 转换为 JSON 格式的多种方法,包括使用 Python、PowerShell 和 Go 编写脚本。

先决条件

如果您想按照本教程中的示例进行操作,请确保您已经

  • 代码编辑器。本文将使用 Visual Studio Code 版本 1.55.1。随意使用您想要的任何代码编辑器。
  • 要开始将 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.9 和 PIP(撰写本文时的最新版本是 21.0.1)。

向 Python 添加 YAML 支持

Python 没有对 YAML 的开箱即用支持。这意味着,Python 默认无法读取或解释 YAML 文档。要将 YAML 支持添加到 Python,您必须首先安装 PyYAML 模块。

要安装 PyYAML 模块,您需要运行 pip 命令,这是 Python 的包安装程序。为此,请按照以下步骤操作。

首先,打开您喜欢的命令解释器,例如命令提示符或 PowerShell。 pip 命令应该适用于任何一种。此示例使用 PowerShell。

接下来,在 PowerShell 中运行以下命令。此命令安装 PyYAML 模块。

pip install pyyaml

正如您在下面的屏幕截图中看到的,pip 安装了最新版本的 PyYAML(撰写本文时为 5.4.1)。

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

编写转换脚本

现在您已经安装了所需的模块 (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
## Import the modules to handle JSON & YAML
import yaml
import json

## Create a variable to hold the data to import
os_list = {}

## Read the YAML file
with open("c:\temp\operating-systems.yml") as infile:
     # Marshall the YAML into the variable defined above os_list = yaml.load(infile, Loader=yaml.FullLoader)     # Print the List to the console. 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:
     # Marshall the JSON, setting "indent" makes the file more readable json.dump(os_list, outfile, indent=4) print("JSON file written.")

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 文件中。

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

3. 最后,打开 convert-os.py Python 脚本应创建的名为 python_operating-systems.json 的 JSON 文件。在此示例中,要在记事本中打开文件,请在 PowerShell 中运行以下命令。

notepad C:\temp\python_operating-systems.json

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

使用 PowerShell 将 YAML 转换为 JSON

PowerShell 能够修改文本文件并将对象转换为多种格式(包括 JSON)。由于 PowerShell 是可扩展的,因此您可以使用 PowerShell 通过正确的模块将 YAML 转换为 JSON 格式。

向 PowerShell 添加 YAML 支持

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. 安装模块后,两个新的 cmdlet 将作为 PowerShell-yaml 模块的一部分在 PowerShell 中可用。这些新的 cmdlet 是:

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

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

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

Get-Command -Module PowerShell-yaml

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

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

编写转换脚本

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

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

2. 复制下面的代码并粘贴到空白的 convert-os.ps1 文件中。下面的代码片段读取 Operating-systems.yml 文件并将其转换为 JSON。进入 JSON 后,它会将 JSON 存储在文件 PowerShell_operating-systems.json 中。

#convert-os.ps1
 #Read the YAML file using Get-Content and convert the data to a hashtable using ConvertFrom-Yaml. The $os_list variable stores the hashtable object.
 $os_list = (Get-Content -Path "C:\temp\operating-systems.yml" | ConvertFrom-Yaml)
 #Convert the hashtable object in the $os_list variable to JSON format using ConvertTo-Json. Once in JSON, save the save to C:\temp\PowerShell_operating-systems.json file using Set-Content.
 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

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

使用 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 包:

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

接下来,复制以下命令并在 PowerShell 中运行它。此命令将下载并安装包名称gopkg.in/yaml.v3

go get gopkg.in/yaml.v3

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

编写转换脚本

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

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

2. 复制以下代码并粘贴到空白 convert-os.go 文件中。该代码导入所需的包,定义一些内存结构,导入 YAML 文件,并在写入名为 c:\temp\go_operating-systems.json 的 JSON 文件之前转换为 JSON。

// This tells go which function to load.
 package main
 // Import packages:
 import (
  // JSON module
     "encoding/json"
  // For writing output to the screen
     "fmt"
  // For reading and wiritng files
     "io/ioutil"
 // YAML module
     "gopkg.in/yaml.v3"
 )
 // Define two "Structs" these are data structures in memory, and match
 // The form of the YAML and JSON files.
 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() {
   // Let the user know the process has started
     fmt.Println("Parsing YAML file")
 // Define the path to the input file
 var fileName string = "c:\temp\operating-systems.yml"
 // Load the YAML from the file. Go requires error handling for this step.
 yamlFile, err := ioutil.ReadFile(fileName)
     if err != nil {
         fmt.Printf("Error reading YAML file: %s\n", err)
         return
     }
 // Extract the YAML into your Struct
     var oses operatingSystems
     yaml.Unmarshal(yamlFile, &oses)
 //Create the JSON Struct, using the data from the YAML Struct
 var osesjson = operatingSystemsjson{
         Windows10:         oses.Windows10,
         WindowsServer2019: oses.WindowsServer2019,
         WindowsServer2022: oses.WindowsServer2022,
         MacOS:             oses.MacOS,
         CentOS:            oses.CentOS,
         Photon:            oses.Photon,
     }
 // Create a string to output in JSON format.
 jsonOutput, err := json.Marshal(osesjson)
 // Print the result to screen. Notice that the %+v means that 
   // the variable name gets printed with the data. This is why
   // there are no spaces in the output Kay names.
     fmt.Printf("Result: %+v\n", osesjson)
 //write the JSON file
 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

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

3. 运行脚本后,打开 convert-os.go 脚本在上一步中创建的输出文件 C:\temp\Go_operating-systems.json。此示例在记事本中打开 Go_operating-systems.json

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

结论

在本文中,您了解了如何使用 Python、PowerShell 和 Go 中的脚本将 YAML 数据和文件转换为 JSON。现在您已经了解了将 YAML 转换为 JSON 的不同方法,您认为您会更多地使用哪种方法?

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯