发布于2019-08-07 09:49 阅读(1243) 评论(0) 点赞(3) 收藏(0)
转载自 https://www.cnblogs.com/dafa638/p/9952790.html
之前都是直接拿sax,或dom等库去解析xml文件为Python的数据类型再去操作,比较繁琐,如今在写Django网站ajax操作时json的解析,发现这篇帖子对这几种数据类型的转换操作提供了另一种更简洁的方法,几种转换方式也都比较全面,转存一下以备不时之需,感谢原创!
注:xml、字典、json、类四种数据的转换,从左到右依次转换,即xml要转换为类时,先将xml转换为字典,再将字典转换为json,
最后将json转换为类。
1、解析xml文件:使用iterfind寻找节点,获取子节点方法 list(节点),获取节点属性 get(属性名),下一级节点的值findtext
from xml.etree.ElementTree import parse try: doc=parse('b.xml') for item in doc.iterfind('class'): classname=item.get('a_name') print("classname=",classname) for s in list(item): name=s.findtext('name') age = s.findtext('age') sex = s.findtext('sex') print("name=",name,"age=",age,"sex=",sex) print("-------------------") except Exception as e: print(e)
2、字典转换为xml文件:使用dicttoxml模块,方法:dicttoxml.dicttoxml(字典数据,根节点名称 custom_root='')import dicttoxml
from xml.dom.minidom import parseString import os d=[20,'name', {'name':'apple','num':10,'price':23}, {'name': 'pear', 'num': 20, 'price': 18.7}, {'name': 'banana', 'num': 10.5, 'price': 23}] bxml=dicttoxml.dicttoxml(d,custom_root='fruit') xml=bxml.decode('utf-8') print(xml) dom=parseString(xml) pxml=dom.toprettyxml(indent=' ') f=open('fruits.xml','w',encoding='utf-8') f.write(pxml) f.close()
3、xml文件转为字典:使用xmltodict模块 ,方法:xmltodict.parse(xml字符串)
import xmltodict import pprint f=open('fruits.xml') xml=f.read() d=xmltodict.parse(xml) pp=pprint.PrettyPrinter(indent=4) pp.pprint(d) f.close()
4、字典转换为json:使用json的dumps方法
import json data={'name':'bill','company':'huawei','age':30} jsonstr=json.dumps(data) print(jsonstr)
5、json转换为字典:使用json模块的loads函数,传入json字符串,返回该字符串对应的字典
d=json.loads(jsonstr) print(d)
6、json转换为类实例,1)、在指定的类中必须有一个接受字典的构造函数;或指定回调函数json2Product; 2)、使用json的loads方法(json字符串,object_hook=类名或者回调函数名)
import json class Product: def __init__(self,d): self.__dict__=d def json2Product(d): return Product(d) f=open('products.json','r',encoding='utf-8') strjson=f.read() products=json.loads(strjson,object_hook=Product) for p in products: print('name=',p.name,'price=',p.price)
7、 类实例转换为json:1)、指定回调函数(product2Dict)2、使用json的dump函数,指定default参数的回调函数import json
def product2Dict(product): return { 'name': product.name, 'price': product.price, 'count': product.count } strJson=json.dumps(products,default=product2Dict) print(strJson)
8、字典转换为类:1)、将字典转换为json 2)、json转换为类
import json data=[{"name": "iPhone9", "price": 9999, "count": 3000}, {"name": "tesila", "price": 800000, "count": 122}] # 将字典转换为json jsonstr=json.dumps(data) class Product: def __init__(self,d): self.__dict__=d def json2Product(d): return Product(d) # 将json转换为类 ps=json.loads(jsonstr,object_hook=Product) for p in ps: print('name=', p.name, 'price=', p.price)
9、将类转换为字典:1)、类转换为json,使用json的dumps方法 2)、json转为字典,使用json的loads方法
def product2Dict(product): return { 'name': product.name, 'price': product.price, 'count': product.count } # 将类转换为json strJson=json.dumps(ps,default=product2Dict) print(strJson) d=json.loads(strJson) print(d)
10、json转xml 1)、先将xml转换为字典 2)、再使用dicttoxml转换为字典
import json import dicttoxml f=open('products.json','r',encoding='utf-8') jsonstr=f.read() # 将json转换为字典 d=json.loads(jsonstr) print(d) # 将字典转换为xml bxml=dicttoxml.dicttoxml(d,custom_root='fruit') print(bxml)
11、将xml转换为json 1)、先使用xmltodict转换为字典2)、再将字典转换为json
import xmltodict import json f=open('products.xml','r',encoding='utf-8') d=f.read() #先将xml转换为字典 data=xmltodict.parse(d) print(data) #再将字典转换为json strjson=json.dumps(data) print(strjson)
作者:9384vfnv
链接:https://www.pythonheidong.com/blog/article/9520/610cbd710aa7b6b6f4ad/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!