当前位置:网站首页>xml-json-yaml 互转
xml-json-yaml 互转
2022-06-09 07:54:00 【黄元宝】
前言: 一个实现了 xml json yaml互转的破脚本,随用随取
- xml_json_yaml_converter.py
""" xml json yaml 互转工具 这个是对 xmltodict 的二次封装 最终这几种数据结构是通过 python 的dict作为中间数据 进行转换的 """ import _io import os import json import yaml import xmltodict from copy import deepcopy from xml.dom import minidom class Converter: def __init__(self): self.data = None self.params = None # 初始参数 def dict2xml(self): if not isinstance(self.data, dict): raise TypeError(f'dict2xml expected a dict but received a { type(self.data)}') if "xml" not in self.data: new = dict() new["xml"] = deepcopy(self.data) self.data = new return xmltodict.unparse(self.data) @staticmethod def _write_xml_format(string, filename): # 试了几种方式 输出的xml都在一行, 所以采用如下方式格式化输出xml dom = minidom.parseString(string) with open(filename, "w") as f: dom.writexml(f, "", "\t", "\n", encoding="utf-8") f.flush() def xml2dict(self): if isinstance(self.data, str): return xmltodict.parse(self.data) elif isinstance(self.data, _io.TextIOWrapper): return xmltodict.parse(self.data.read()) raise TypeError(f'xml2dict expected a string or _io.TextIOWrapper, but received a { self.data}') def dict2yaml(self): if not isinstance(self.data, dict): raise TypeError(f'dict2yaml expected a dict but received a { type(self.data)}') return yaml.safe_dump(self.data) def yaml2dict(self): if isinstance(self.data, str): return yaml.safe_load(self.data) elif isinstance(self.data, _io.TextIOWrapper): return yaml.safe_load(self.data) raise TypeError(f'from_yaml expected a string or _io.TextIOWrapper, but received a { self.data}') def dict2json(self): if not isinstance(self.data, dict): raise TypeError(f'to_json expected a dict but received a { type(self.data)}') return json.dumps(self.data, indent=4) def json2dict(self): if isinstance(self.data, str): return json.loads(self.data) elif isinstance(self.data, _io.TextIOWrapper): return json.load(self.data) raise TypeError(f'from_json expected a string or _io.TextIOWrapper, but received a { self.data}') def _fd(self, data): """返回文件句柄 带后缀的文件名称 将先进入这里 open 返回句柄""" return open(data, encoding="utf-8") # -------------------------------------------- 以上全是 dict 和 结构互转 下面是接口 ---------------------------------- def pre_converter(self, data): self.params = data if isinstance(data, str): endswith = os.path.splitext(data) if len(endswith) == 2: # 传参是 一个带后缀的文件地址 self.data = self._fd(data) self.params = endswith[0] # 拿到前缀作为输出的文件前缀 else: self.data = data def hook_converter(self, value, endswith): # 转换后的操作 写入文件之类 if self.params is not None: filename = self.params + "." + endswith if endswith == "xml": self._write_xml_format(value, filename) else: with open(filename, "w") as f: f.write(value) f.flush() def xml2json(self, data): self.pre_converter(data) self.data = self.xml2dict() value = self.dict2json() self.hook_converter(value, "json") def xml2yaml(self, data): self.pre_converter(data) self.data = self.xml2dict() value = self.dict2yaml() self.hook_converter(value, "yaml") def json2xml(self, data): self.pre_converter(data) self.data = self.json2dict() value = self.dict2xml() self.hook_converter(value, "xml") def json2yaml(self, data): self.pre_converter(data) self.data = self.json2dict() value = self.dict2yaml() self.hook_converter(value, "yaml") def yaml2xml(self, data): self.pre_converter(data) self.data = self.yaml2dict() value = self.dict2xml() self.hook_converter(value, "xml") def yaml2json(self, data): self.pre_converter(data) self.data = self.yaml2dict() value = self.dict2json() self.hook_converter(value, "json") if __name__ == '__main__': import fire fire.Fire(Converter) - 命令
是一个简单的命令行,做太多功能,简陋一点- python3 xml_json_yaml_converter.py xml2json xx.xml
在当前目录下生成同名的json文件 - python3 xml_json_yaml_converter.py json2xml xx.json
在当前目录下生成同名的xml文件 - …
其余命令参考上面
- python3 xml_json_yaml_converter.py xml2json xx.xml
边栏推荐
- MySQL: merge query results and aliases
- C语言复习9
- 「冲刺大厂基础2」
- Lvs+keepalived high availability
- (13) Cross compilation and memory leak detection of Valgrind on ARM
- Web performance test case design model
- SQL or NoSQL, you will understand after reading this article
- PostgreSQL database replication - background first-class citizen process walreceiver extracts information
- TCP connection establishment and termination, TCP state transition
- Pycharm and MySQL as a student information management system
猜你喜欢

Robot_ Framework: Variables

Selenium: Introduction

Taobao classification encyclopedia and its grouping (mysql, XLS) files, hierarchical relationship, spelling, hierarchy, hierarchical tree, tips, data on February 28, 2022

软件设计文档最容易忽略哪些?

Dbutil auxiliary class, manual commit transaction, metadata

2022年全國最新消防設施操作員(中級消防設施操作員)考試模擬題庫及答案

mysql知识点总结

Mechanical keyboard shaft (red shaft, tea shaft, black shaft, green shaft)

Redis large key

Oracle: subquery, sorting
随机推荐
Sqlzoo question brushing record-2
Special places of to documents of SAP WM 2-step picking
[NewOJ Week 1]---CDE
2022 Chinese cook (elementary) examination question bank and online simulation examination
Specific steps for yolov5 to add attention mechanism
Oracle: Foundation
[learning records of the first week in June] UU computer vision (1):3d Reconstruction & camera calibration
[cloud resident co creation] data center pue optimization model generation service: a money saving strategy for data centers under the AI wave, just use these tips
Which software design documents are most easily ignored?
It took so long for numpy to really use the ndarray object
Redis large key
error converting YAML to JSON: yaml: line 10: found character that cannot start any token
Use of thread pool
Market Research - current situation and future development trend of ethylene absorbent package market in the world and China
Simple practice of bouncing shell with NC and Bash
mysql知识点总结
R language through rprofile Site file, custom configuration of R language development environment startup parameters, shutdown parameters, use file Edit function edit configuration file
PHP get last Monday, get the last week date of the specified date, last Monday
Résumé des connaissances de base redis (hyper détaillé)
CV学习笔记-CNN-VGG