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

 更新时间:2022年07月27日 17:06:10   作者:将冲破艾迪i  
这篇文章主要为大家详细介绍了如何利用Python语言实现yaml与json文件的批量互转,文中的示例代码讲解详细,感兴趣的小伙伴可以动手尝试一下

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

代码如下:

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"    
         }
    }
}

代码如下:

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批量移动文件

    用python批量移动文件

    这篇文章主要介绍了如何用python批量移动文件,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2021-01-01
  • Python绘图之桃花盛开

    Python绘图之桃花盛开

    这篇文章主要介绍了如何用python绘制桃花树,帮助大家更好的使用python处理图片,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-08-08
  • Python中将列表转化为链表的方法详解

    Python中将列表转化为链表的方法详解

    这篇文章主要介绍了Python中将列表转化为链表的方法详解,本文的主要问题是输入一组数,将其按照顺序添加到链表中,文中提供了解决思路与部分实现代码,需要的朋友可以参考下
    2023-11-11
  • Python3之外部文件调用Django程序操作model等文件实现方式

    Python3之外部文件调用Django程序操作model等文件实现方式

    这篇文章主要介绍了Python3之外部文件调用Django程序操作model等文件实现方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • openCV实现图像融合的示例代码

    openCV实现图像融合的示例代码

    图像融合是两幅图片叠加在一起,本文主要介绍了openCV实现图像融合的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • 利用python将 Matplotlib 可视化插入到 Excel表格中

    利用python将 Matplotlib 可视化插入到 Excel表格中

    这篇文章主要介绍了利用python将 Matplotlib 可视化 插入到 Excel 表格中,通过使用xlwings模块来控制Excel插入图表,具体详细需要的朋友可以参考下面文章内容
    2022-06-06
  • Python Web框架之Django框架Model基础详解

    Python Web框架之Django框架Model基础详解

    这篇文章主要介绍了Python Web框架之Django框架Model基础,结合实例形式分析了Django框架Model模型相关使用技巧与操作注意事项,需要的朋友可以参考下
    2019-08-08
  • python字符串加密解密的三种方法分享(base64 win32com)

    python字符串加密解密的三种方法分享(base64 win32com)

    这篇文章主要介绍了python字符串加密解密的三种方法,包括用base64、使用win32com.client、自己写的加密解密算法三种方法,大家参考使用吧
    2014-01-01
  • Python图片批量自动抠图去背景的代码详解

    Python图片批量自动抠图去背景的代码详解

    这篇文章主要介绍了Python图片批量自动抠图去背景,只要上传图片,就可以自动把背景去掉把目标对象抠出来,非常方便,对Python图片批量自动抠图去背景的代码感兴趣的朋友一起看看吧
    2022-03-03
  • pandas如何灵活增加新的空字段

    pandas如何灵活增加新的空字段

    这篇文章主要介绍了pandas如何灵活增加新的空字段问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08

最新评论