×
您的位置: 首页 > 编程笔记

Python中xml、字典、json、类四种数据的转换

Python Python 3 JSON XML 时间:2019-08-06  查看:800   收藏

之前都是直接拿sax,或dom等库去解析xml文件为Python的数据类型再去操作,比较繁琐,如今在写Django网站ajax操作时json的解析,发现这篇帖子对这几种数据类型的转换操作提供了另一种更简洁的方法,几种转换方式也都比较全面,转存一下以备不时之需,感谢原创!

注:xml、字典、json、类四种数据的转换,从左到右依次转换,即xml要转换为类时,先将xml转换为字典,再将字典转换为json,
最后将json转换为类。
from xml.etree.ElementTree import parsetry:
    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 parseStringimport  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 xmltodictimport 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方法
={:,:,:30=
5、json转换为字典:使用json模块的loads函数,传入json字符串,返回该字符串对应的字典
d=json.loads(jsonstr)print(d)
6、json转换为类实例,1)、在指定的类中必须有一个接受字典的构造函数;或指定回调函数json2Product;                     2)、使用json的loads方法(json字符串,object_hook=类名或者回调函数名)
import jsonclass Product:def __init__(self,d):
        self.__dict__=ddef 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}]# 将字典转换为jsonjsonstr=json.dumps(data)class Product:def __init__(self,d):
        self.__dict__=ddef 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
        }# 将类转换为jsonstrJson=json.dumps(ps,default=product2Dict)print(strJson)
d=json.loads(strJson)print(d)
10、json转xml 1)、先将xml转换为字典 2)、再使用dicttoxml转换为字典
import jsonimport dicttoxml
f=open('products.json','r',encoding='utf-8')
jsonstr=f.read()# 将json转换为字典d=json.loads(jsonstr)print(d)# 将字典转换为xmlbxml=dicttoxml.dicttoxml(d,custom_root='fruit')print(bxml)
11、将xml转换为json  1)、先使用xmltodict转换为字典2)、再将字典转换为json
import xmltodictimport json
f=open('products.xml','r',encoding='utf-8')
d=f.read()#先将xml转换为字典data=xmltodict.parse(d)print(data)#再将字典转换为jsonstrjson=json.dumps(data)print(strjson)

 

 

0% (0)
0% (0)