zoukankan      html  css  js  c++  java
  • 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)


  • 相关阅读:
    Java ConcurrentModificationException 异常分析与解决方案
    android studio 怎么做屏幕适配?
    java Class.getSimpleName() 的用法
    LeetCode——Remove Element
    用WidgeDuino创建一个SCADA(监控与数据採集)系统
    【Oracle】OCR的备份和恢复之导出导入
    Java大数类介绍
    POJ 1113 Wall 凸包
    OPENCV中滑动条的使用
    Android
  • 原文地址:https://www.cnblogs.com/trieagle/p/11063208.html
Copyright © 2011-2022 走看看