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

作者:将冲破艾迪i 时间:2023-11-20 07:07:54 

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)

来源:https://blog.csdn.net/aidijava/article/details/125630629

标签:Python,yaml,json
0
投稿

猜你喜欢

  • python 对excel交互工具的使用详情

    2021-11-25 19:10:06
  • css网页下拉菜单制作方法(4):定位问题

    2007-02-03 11:39:00
  • Python3 执行系统命令并获取实时回显功能

    2023-12-06 13:23:10
  • 提高MySQL数据库查询效率的三个实用技巧

    2008-12-03 16:40:00
  • 判断python字典中key是否存在的两种方法

    2023-08-19 00:18:05
  • Python如何对齐字符串

    2023-05-30 01:21:11
  • JavaScript Base64编码和解码,实现URL参数传递。

    2024-04-22 22:45:32
  • TensorFlow的自动求导原理分析

    2023-06-14 15:22:02
  • python多线程操作实例

    2022-09-22 12:21:34
  • Python使用read_csv读数据遇到分隔符问题的2种解决方式

    2022-01-13 13:30:47
  • 大数据就业的三大方向和最热门十大岗位【推荐】

    2023-05-18 16:21:06
  • 分组字符合并SQL语句 按某字段合并字符串之一(简单合并)

    2024-01-24 11:30:20
  • python3 tcp的粘包现象和解决办法解析

    2022-08-02 02:22:53
  • python实现给微信公众号发送消息的方法

    2021-08-25 23:44:57
  • PHP和JavaScrip分别获取关联数组的键值示例代码

    2023-06-16 05:30:51
  • python 使用matplotlib 实现从文件中读取x,y坐标的可视化方法

    2023-07-29 05:25:42
  • Go 中 time.After 可能导致的内存泄露问题解析

    2024-02-03 13:05:16
  • Python flask路由间传递变量实例详解

    2021-03-13 16:30:16
  • pycharm运行出现ImportError:No module named的解决方法

    2022-09-10 18:06:23
  • Go中strings的常用方法详解

    2023-06-27 01:58:32
  • asp之家 网络编程 m.aspxhome.com