[玩转系统] 如何将 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)。
编写转换脚本
现在您已经安装了所需的模块 (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 文件中。
3. 最后,打开 convert-os.py Python 脚本应创建的名为 python_operating-systems.json 的 JSON 文件。在此示例中,要在记事本中打开文件,请在 PowerShell 中运行以下命令。
notepad C:\temp\python_operating-systems.json
使用 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 转换 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 转换脚本,请按照以下步骤操作。
- 如果您尚未打开 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
使用 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 转换 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
3. 运行脚本后,打开 convert-os.go 脚本在上一步中创建的输出文件 C:\temp\Go_operating-systems.json。此示例在记事本中打开 Go_operating-systems.json。
结论
在本文中,您了解了如何使用 Python、PowerShell 和 Go 中的脚本将 YAML 数据和文件转换为 JSON。现在您已经了解了将 YAML 转换为 JSON 的不同方法,您认为您会更多地使用哪种方法?
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag