Python实现yaml与json文件批量互转

晚来风
晚来风
发布时间:2026-10-15 | 5人浏览过
原创

本文详细介绍如何使用Python库实现YAML与JSON格式文件的相互转换。内容涵盖环境配置、单文件转换代码示例,以及利用自定义类实现指定目录下文件的批量转换功能。重点解析了sort_keys参数对输出顺序的影响,并提供完整的Python代码供参考。

1. 安装yaml库

若需利用Python完成YAML与JSON格式之间的相互转换,首先需确保已安装pip工具,随后通过pip命令安装yaml相关依赖库。

关于pip的具体下载流程及使用方法,可查阅:pip的安装与使用,解决pip下载速度慢的问题

执行以下命令以安装yaml库:

pip install pyyaml

2. yaml转json

创建一个名为test.yaml的文件,并在其中写入如下内容:

A:
     hello:
          name: Michael    
          address: Beijing 
          
B:
     hello:
          name: jack 
          address: Shanghai

对应的Python转换代码如下:

import yaml
import json

# yaml文件内容转换成json格式
def yaml_to_json(yamlPath):
    with open(yamlPath, encoding="utf-8") as f:
        datas = yaml.load(f,Loader=yaml.FullLoader)  # 将文件的内容转换为字典形式
    jsonDatas = json.dumps(datas, indent=5) # 将字典的内容转换为json格式的字符串
    print(jsonDatas)

if __name__ == "__main__":
    jsonPath = 'E:/Code/Python/test/test.yaml'
    yaml_to_json(jsonPath)
    

运行上述代码后,输出结果如下:

{ "A": { "hello": { "name": "Michael", "address": "Beijing" } }, "B": { "hello": { "name": "jack", "address": "Shanghai" } } }

3. json转yaml

新建一个test.json文件,并填入以下数据:

{
    "A": {
         "hello": {
            "name": "Michael",
            "address": "Beijing"           
         }
    },
    "B": {
         "hello": {
            "name": "jack",
            "address": "Shanghai"    
         }
    }
}

实现该转换的Python代码如下:

import yaml
import json

# json文件内容转换成yaml格式
def json_to_yaml(jsonPath):
    with open(jsonPath, encoding="utf-8") as f:
        datas = json.load(f) # 将文件的内容转换为字典形式
    yamlDatas = yaml.dump(datas, indent=5, sort_keys=False) # 将字典的内容转换为yaml格式的字符串
    print(yamlDatas)

if __name__ == "__main__":
    jsonPath = 'E:/Code/Python/test/test.json'
    json_to_yaml(jsonPath)

执行该脚本后的输出结果如下:

A: hello: name: Michael address: Beijing B: hello: name: jack address: Shanghai

需要注意的是,若在调用转换函数时未指定sort_keys=False参数,系统默认会对键名进行排序,此时执行结果将变为:

A: hello: address: Beijing name: Michael B: hello: address: Shanghai name: jack

4. 批量将yaml与json文件互相转换

实现YAML与JSON文件批量相互转换的核心逻辑如下:

import yaml
import json
import os
from pathlib import Path
from fnmatch import fnmatchcase

class Yaml_Interconversion_Json:
    def __init__(self):
        self.filePathList = []
    
    # yaml文件内容转换成json格式
    def yaml_to_json(self, yamlPath):
        with open(yamlPath, encoding="utf-8") as f:
            datas = yaml.load(f,Loader=yaml.FullLoader)  
        jsonDatas = json.dumps(datas, indent=5)
        # print(jsonDatas)
        return jsonDatas

    # json文件内容转换成yaml格式
    def json_to_yaml(self, jsonPath):
        with open(jsonPath, encoding="utf-8") as f:
            datas = json.load(f)
        yamlDatas = yaml.dump(datas, indent=5)
        # print(yamlDatas)
        return yamlDatas

    # 生成文件
    def generate_file(self, filePath, datas):
        if os.path.exists(filePath):
            os.remove(filePath)	
        with open(filePath,'w') as f:
            f.write(datas)

    # 清空列表
    def clear_list(self):
        self.filePathList.clear()

    # 修改文件后缀
    def modify_file_suffix(self, filePath, suffix):
        dirPath = os.path.dirname(filePath)
        fileName = Path(filePath).stem + suffix
        newPath = dirPath + '/' + fileName
        # print('{}_path:{}'.format(suffix, newPath))
        return newPath

    # 原yaml文件同级目录下,生成json文件
    def generate_json_file(self, yamlPath, suffix ='.json'):
        jsonDatas = self.yaml_to_json(yamlPath)
        jsonPath = self.modify_file_suffix(yamlPath, suffix)
        # print('jsonPath:{}'.format(jsonPath))
        self.generate_file(jsonPath, jsonDatas)

    # 原json文件同级目录下,生成yaml文件
    def generate_yaml_file(self, jsonPath, suffix ='.yaml'):
        yamlDatas = self.json_to_yaml(jsonPath)
        yamlPath = self.modify_file_suffix(jsonPath, suffix)
        # print('yamlPath:{}'.format(yamlPath))
        self.generate_file(yamlPath, yamlDatas)

    # 查找指定文件夹下所有相同名称的文件
    def search_file(self, dirPath, fileName):
        dirs = os.listdir(dirPath) 
        for currentFile in dirs: 
            absPath = dirPath + '/' + currentFile 
            if os.path.isdir(absPath): 
                self.search_file(absPath, fileName)
            elif currentFile == fileName:
                self.filePathList.append(absPath)

    # 查找指定文件夹下所有相同后缀名的文件
    def search_file_suffix(self, dirPath, suffix):
        dirs = os.listdir(dirPath) 
        for currentFile in dirs: 
            absPath = dirPath + '/' + currentFile 
            if os.path.isdir(absPath):
                if fnmatchcase(currentFile,'.*'): 
                    pass
                else:
                    self.search_file_suffix(absPath, suffix)
            elif currentFile.split('.')[-1] == suffix: 
                self.filePathList.append(absPath)

    # 批量删除指定文件夹下所有相同名称的文件
    def batch_remove_file(self, dirPath, fileName):
        self.search_file(dirPath, fileName)
        print('The following files are deleted:{}'.format(self.filePathList))
        for filePath in self.filePathList:
            if os.path.exists(filePath):
                os.remove(filePath)	
        self.clear_list()

    # 批量删除指定文件夹下所有相同后缀名的文件
    def batch_remove_file_suffix(self, dirPath, suffix):
        self.search_file_suffix(dirPath, suffix)
        print('The following files are deleted:{}'.format(self.filePathList))
        for filePath in self.filePathList:
            if os.path.exists(filePath):
                os.remove(filePath)	
        self.clear_list()

    # 批量将目录下的yaml文件转换成json文件
    def batch_yaml_to_json(self, dirPath):
        self.search_file_suffix(dirPath, 'yaml')
        print('The converted yaml file is as follows:{}'.format(self.filePathList))
        for yamPath in self.filePathList:
            try:
                self.generate_json_file(yamPath)
            except Exception as e:
                print('YAML parsing error:{}'.format(e))         
        self.clear_list()

    # 批量将目录下的json文件转换成yaml文件
    def batch_json_to_yaml(self, dirPath):
        self.search_file_suffix(dirPath, 'json')
        print('The converted json file is as follows:{}'.format(self.filePathList))
        for jsonPath in self.filePathList:
            try:
                self.generate_yaml_file(jsonPath)
            except Exception as e:
                print('JSON parsing error:{}'.format(jsonPath))
                print(e)
        self.clear_list()

if __name__ == "__main__":
    dirPath = 'C:/Users/hwx1109527/Desktop/yaml_to_json'
    fileName = 'os_deploy_config.yaml'
    suffix = 'yaml'
    filePath = dirPath + '/' + fileName
    yaml_interconversion_json = Yaml_Interconversion_Json()
    yaml_interconversion_json.batch_yaml_to_json(dirPath)
    # yaml_interconversion_json.batch_json_to_yaml(dirPath)
    # yaml_interconversion_json.batch_remove_file_suffix(dirPath, suffix)

至此,关于Python实现YAML与JSON文件批量互转的教程已介绍完毕。如需了解更多相关Python YAML与JSON互转的内容,建议搜索本站历史文章或继续浏览下方的相关文章。感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表