Python中xml、字典、json、類四種數據的轉換


最近學python,覺得python很強很大很強大,寫一個學習隨筆,當作留念
注: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)



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM