How to use python json and xml, convert between json and dictionary, manipulate json and xml format files

import json

a={"x":10}
#Dictionary b=json.dumps(a) #Dictionary to json, the value of b is'{"x": 10}'. When the field is {"y":None}, it will be'{"y": null}' when converted to json
c=(1,2,3,4)
json.dumps© #The value of tuple converted to json is' [1, 2, 3, 4]', tuples will be converted to lists, None will be converted to null, and other conversions will not change
d={"c":3,"b":2,"a" :1}
e=json.dumps(d,sort_keys=True,indent=4,separators=(',',':')) #You can add parameters when converting json, whether sort_keys are sorted or not, indent uses indentation to distinguish levels, separators represent separators with specified symbols.
f=json.loads(e) #Convert json to a dictionary, where null will be converted to None, and the others will remain unchanged

There are three ways of xml parsing:
1.dom (put the entire xml in memory, high efficiency)
2. sax (read line by line from the xml file,
saving memory) 3.etree (positioning by Xpath)
Insert picture description here

Operate xml format files
from xml.dom.minidom import parse
import xml.dom.minidom

a=xml.dom.mimidom.parse(“E:\a.xml”) #Get a.xml file
b=a.documentElement #Get the root element collection of
a.xml c=b.getAttribute(“shelf”) # Get the shelf attribute of the root element of
a.xml d=b.getElementsByTagName("movie") #Get the specified child node under the b node movie
f=d[0] #Get the first node under the d node type
g=f. tagName
#Get the tag name of the f node h=f.toxml() #Get all the content under the f node
i=f.getElementsByTagName("type") [0].childNodes[0].data #Get the "War" in the type tag , The content of Thriller' text. childNodes means to get a list of all child nodes under the type node, data means to get the text content

Guess you like

Origin blog.csdn.net/weixin_44123630/article/details/112438414