Python xml、字典、json、类四种数据类型如何实现互相转换

2020-05-27,,

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

注: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)#可以通过d['root']['arg']['#text']来访问节点中的文本值,d['root']['arg']['@p']来访问属性值
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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

《Python xml、字典、json、类四种数据类型如何实现互相转换.doc》

下载本文的Word格式文档,以方便收藏与打印。