SoFunction
Updated on 2024-11-16

Python xml, dictionary, json, class four data types how to realize each other conversion

Before are directly take sax, or dom and other libraries to parse the xml file for Python data types and then go to the operation, more cumbersome, now in the ajax operation of the Django site to write json parsing, and found that this post on the conversion of these data types provides another more concise method of operation, xmltodict and dicttoxml libraries! credit, several conversion methods are also more comprehensive, to save for emergencies, thanks to the original collation!

Note:xml, dictionary, json, class conversion of four kinds of data, from left to right in order of conversion, that is, xml to be converted to class, the first xml into a dictionary, and then the dictionary into json.
Finally the json is converted to a class.

1, parse the xml file: use iterfind to find nodes, get child nodes method list (node), get node attributes get (attribute name), the value of the next level node findtext

from  import parse
try:
  doc=parse('')
  for item in ('class'):
      classname=('a_name')
      print("classname=",classname)
      for s in list(item):
        name=('name')
        age = ('age')
        sex = ('sex')
        print("name=",name,"age=",age,"sex=",sex)
      print("-------------------")
except Exception as e:
  print(e)

2, the dictionary is converted to xml file: the use of dicttoxml module, method: (dictionary data, root node name custom_root = '') import dicttoxml

from  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=(d,custom_root='fruit')
xml=('utf-8')
print(xml)
dom=parseString(xml)
pxml=(indent='  ')
f=open('','w',encoding='utf-8')
(pxml)
()

3, xml file into a dictionary: the use of xmltodict module , method: (xml string)

import xmltodict
import pprint
f=open('')
xml=()
d=(xml)
pp=(indent=4)
(d)#Can access text values in nodes via d['root']['arg']['#text'], and attribute values via d['root']['arg']['@p']
()

4, the dictionary is converted to json: the use of json dumps method

import json
data={'name':'bill','company':'huawei','age':30}
jsonstr=(data)
print(jsonstr)

5, json converted to a dictionary: use the loads function of the json module, pass in the json string, return the string corresponding to the dictionary

d=(jsonstr)
print(d)

6. json is converted to a class instance.

1), in the specified class must have a constructor that accepts dictionaries; or specify the callback function json2Product;

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('','r',encoding='utf-8')
strjson=()
products=(strjson,object_hook=Product)
for p in products:
  print('name=',,'price=',)

7, class instances converted to json: 1), specify the callback function (product2Dict) 2, the use of json dump function, specify the default parameters of the callback function import json

def product2Dict(product):
  return {
    'name': ,
    'price': ,
    'count': 
    }
strJson=(products,default=product2Dict)
print(strJson)

8, the dictionary is converted to class: 1), the dictionary is converted to json 2), json is converted to class

import json
data=[{"name": "iPhone9", "price": 9999, "count": 3000}, {"name": "tesila", "price": 800000, "count": 122}]
# Convert dictionary to json
jsonstr=(data)
class Product:
  def __init__(self,d):
    self.__dict__=d
def json2Product(d):
  return Product(d)
# Convert json to class
ps=(jsonstr,object_hook=Product)
for p in ps:
  print('name=', , 'price=', )

9, the class will be converted to a dictionary: 1), the class is converted to json, using json dumps method 2), json to a dictionary, using json loads method

def product2Dict(product):
  return {
    'name': ,
    'price': ,
    'count': 
    }
# Convert classes to json
strJson=(ps,default=product2Dict)
print(strJson)
d=(strJson)
print(d)

10, json to xml 1), the first xml converted to dictionary 2), and then use dicttoxml converted to dictionary

import json
import dicttoxml
f=open('','r',encoding='utf-8')
jsonstr=()
# Convert json to dictionary
d=(jsonstr)
print(d)
# Convert dictionary to xml
bxml=(d,custom_root='fruit')
print(bxml)

11, will be converted from xml to json 1), the first use of xmltodict converted to a dictionary 2), and then the dictionary is converted to json

import xmltodict
import json
f=open('','r',encoding='utf-8')
d=()
# Convert xml to dictionary first
data=(d)
print(data)
# then convert the dictionary to json
strjson=(data)
print(strjson)

This is the whole content of this article.