使用python实现json, yaml 互转
1. 安装yaml库:
2. yaml转json
新建一个test.yaml文件,添加以下内容:
| A: |
| hello: |
| name: Michael |
| address: Beijing |
| B: |
| hello: |
| name: jack |
| address: Shanghai |
| import yaml |
| import 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) |
| print(jsonDatas) |
| |
| if __name__ == "__main__": |
| yamlPath = 'E:/Code/Python/test/test.yaml' |
| yaml_to_json(yamlPath) |
3. json转yaml
新建一个test.json文件,添加以下内容:
| { |
| "A": { |
| "hello": { |
| "name": "Michael", |
| "address": "Beijing" |
| } |
| }, |
| "B": { |
| "hello": { |
| "name": "jack", |
| "address": "Shanghai" |
| } |
| } |
| } |
| |
| import yaml |
| import json |
| |
| |
| 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) |
| print(yamlDatas) |
| |
| if __name__ == "__main__": |
| jsonPath = 'E:/Code/Python/test/test.json' |
| json_to_yaml(jsonPath) |
如果不加sort_keys=False,那么默认是排序的
4. 批量将yaml与json文件互相转换
定义了一个Yaml_Interconversion_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 = [] |
| |
| |
| 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) |
| |
| return jsonDatas |
| |
| |
| def json_to_yaml(self, jsonPath): |
| with open(jsonPath, encoding="utf-8") as f: |
| datas = json.load(f) |
| yamlDatas = yaml.dump(datas, indent=5, sort_keys=False) |
| |
| 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 |
| |
| return newPath |
| |
| |
| def generate_json_file(self, yamlPath, suffix ='.json'): |
| jsonDatas = self.yaml_to_json(yamlPath) |
| jsonPath = self.modify_file_suffix(yamlPath, suffix) |
| |
| self.generate_file(jsonPath, jsonDatas) |
| |
| |
| def generate_yaml_file(self, jsonPath, suffix ='.yaml'): |
| yamlDatas = self.json_to_yaml(jsonPath) |
| yamlPath = self.modify_file_suffix(jsonPath, suffix) |
| |
| 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() |
| |
| |
| 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() |
| |
| |
| 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 = 'E:/Code/Python/test' |
| yaml_interconversion_json = Yaml_Interconversion_Json() |
| yaml_interconversion_json.batch_yaml_to_json(dirPath) |
Yaml_Interconversion_Json类中函数的介绍:
| yaml_to_json():把yaml文件内容转换成json格式,并返回json格式数据 |
| json_to_yaml():把json文件内容转换成yaml格式,并返回yaml格式数据 |
| generate_json_file():原yaml文件同级目录下,生成json文件 |
| generate_yaml_file():原json文件同级目录下,生成yaml文件 |
| batch_yaml_to_json():批量将目录下的yaml文件转换成json文件 |
| batch_json_to_yaml():批量将目录下的json文件转换成yaml文件 |
| batch_remove_file(): 批量删除指定文件夹下所有相同名称的文件 |
| batch_remove_file_suffix():批量删除指定文件夹下所有相同后缀名的文件 |
https://blog.csdn.net/aidijava/article/details/125630629
https://www.jianshu.com/p/d28d33e52aaa
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY