Conversion of xml, dictionary, json and class data in Python

Posted by Drezek on Tue, 06 Aug 2019 09:41:02 +0200

Reproduced from https://www.cnblogs.com/dafa638/p/9952790.html

 

sax, or dom and other libraries were used to parse xml files for Python data types and then to operate. It is more cumbersome. It is found that this post provides a more concise method for the conversion of these data types. Several conversion methods are also more comprehensive. Transfer for occasional needs. Thank you for the original!

Note: xml, dictionary, JSON and class are converted from left to right. When XML is converted to class, XML is first converted to dictionary and then to json.
Finally, json is transformed into a class.
1. parse xml file: use iterfind to find nodes, get the method list of sub-nodes (nodes), get the attributes of nodes (attribute names), the value of findtext of the next node
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. Dictionary conversion to xml file: using dicttoxml module, method: dicttoxml. dicttoxml (dictionary data, root node name 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. Converting XML file to dictionary: using xmltodict module, method: xmltodict.parse(xml string)
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. Dictionary conversion to json: using json's dumps method
import json
data={'name':'bill','company':'huawei','age':30}
jsonstr=json.dumps(data)
print(jsonstr)
5. json to dictionary: using the loads function of json module, the json string is passed in and the dictionary corresponding to the string is returned
d=json.loads(jsonstr)
print(d)
6. JSON is converted to class instance, 1) there must be a constructor accepting dictionary in the specified class, or a callback function json2Product is specified;
                     2) Use json's loads method (json string, object_hook = class name or callback function name)
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. Converting class instance to json:1, specifying callback function (product 2Dict) 2, using dump function of json, specifying callback function import json with default parameter
def product2Dict(product):
    return {
        'name': product.name,
        'price': product.price,
        'count': product.count
        }
strJson=json.dumps(products,default=product2Dict)
print(strJson)
8. Converting dictionaries to classes: 1), converting dictionaries to json 2, and json to classes
import json
data=[{"name": "iPhone9", "price": 9999, "count": 3000}, {"name": "tesila", "price": 800000, "count": 122}]
# Converting a dictionary to json
jsonstr=json.dumps(data)
class Product:
    def __init__(self,d):
        self.__dict__=d
def json2Product(d):
    return Product(d)
# take json Converting to a class
ps=json.loads(jsonstr,object_hook=Product)
for p in ps:
    print('name=', p.name, 'price=', p.price)
9. Convert classes to dictionaries: 1), classes to json, using json's dumps method 2, JSON to dictionary, using json's loads method
def product2Dict(product):
    return {
        'name': product.name,
        'price': product.price,
        'count': product.count
        }
# Converting classes to json
strJson=json.dumps(ps,default=product2Dict)
print(strJson)
d=json.loads(strJson)
print(d)
10. json to xml 1, xml to dictionary 2, dicttoxml to dictionary
import json
import dicttoxml
f=open('products.json','r',encoding='utf-8')
jsonstr=f.read()
# take json Converting to a dictionary
d=json.loads(jsonstr)
print(d)
# Converting a dictionary to xml
bxml=dicttoxml.dicttoxml(d,custom_root='fruit')
print(bxml)
11. Convert xml to json 1, use xmltodict to dictionary 2, and then convert dictionary to json
import xmltodict
import json
f=open('products.xml','r',encoding='utf-8')
d=f.read()
#First will xml Converting to a dictionary
data=xmltodict.parse(d)
print(data)
#Convert the dictionary to json
strjson=json.dumps(data)
print(strjson)

Topics: PHP JSON xml encoding Python