Python中xml和json格式互转
来源:互联网 发布:兄弟情义歌曲网络歌手 编辑:程序博客网 时间:2024/06/15 14:46
Python中xml和json格式是可以互转的,就像json格式转Python字典对象那样。
xml格式和json格式互转用到的xmltodict库
安装xmltodict库
C:\Users\Administrator>pip3 install xmltodictCollecting xmltodict Downloading xmltodict-0.11.0-py2.py3-none-any.whlInstalling collected packages: xmltodictSuccessfully installed xmltodict-0.11.0利用pip可以直接安装。
xml格式转json格式
import jsonimport xmltodict#定义xml转json的函数def xmltojson(xmlstr): #parse是的xml解析器 xmlparse = xmltodict.parse(xmlstr) #json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。 #dumps()方法的ident=1,格式化json jsonstr = json.dumps(xmlparse,indent=1) print(jsonstr)if __name__ == "__main__": xml =""" #需要转换json格式的xml<student> <stid>10213</stid> <info> <name>name</name> <sex>male</sex> </info> <course> <name>math</name> <score>90</score> </course></student> """ xmltojson(xml) #调用转换函数
json格式转xml格式
import xmltodict#json转xml函数def jsontoxml(jsonstr): #xmltodict库的unparse()json转xml xmlstr = xmltodict.unparse(jsonstr) print(xmlstr)if __name__ == "__main__": json = {'student': {'course': {'name': 'math', 'score': '90'}, 'info': {'sex': 'male', 'name': 'name'}, 'stid': '10213'}} jsontoxml(json)结果:
C:\python35\python.exe "D:/自动化测用例/json to xml.py"
<?xml version="1.0" encoding="utf-8"?>
<student><course><name>math</name><score>90</score></course><info><name>name</name><sex>male</sex></info><stid>10213</stid></student>
Process finished with exit code 0
参考:
http://www.crifan.com/python_convertion_between_xml_and_json/?utm_source=tuicool&utm_medium=referral
1 0
- Python中xml和json格式互转
- python中将xml格式转json格式
- (转)Ajax中XML和JSON格式的优劣比较
- xml和json互转的格式,结构
- JSON和XML格式转换
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- Ajax中XML和JSON格式的优劣比较
- WindowsPhone中XML和Json格式的数据解析
- Python 操作xml转换为json格式
- 网站的海量数据和高并发的解决方案(二)
- 数据结构初步
- thinkphp,thinkphp5的唯一验证问题
- Android开发中一些命名规范
- 基于proteus的51单片机仿真实例五十三、4个按键的组成的按键扫描实例
- Python中xml和json格式互转
- sicp in python
- KMP简单模板
- Windows Server2012虚拟内存设置
- 基于proteus的51单片机仿真实例五十四、中断的概念和外部中断实例1
- jQuery中$(document).ready与Javascript中window.onload区别
- 深入理解JS原型链
- 阿姆达尔定律(Amdahl's law)
- [C++]STL中vector容器 begin()与end()函数、front()与back()的用法