新聞中心
本篇內(nèi)容介紹了“Python怎么將xml格式轉(zhuǎn)換為json格式”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
在Python編程中,經(jīng)常遇到xml格式的文件或字符串。由于json格式的方便性,常常希望將xml格式轉(zhuǎn)換為json格式來處理,這可以通過模塊xmltodict來實(shí)現(xiàn)。
xmltodict模塊通過pip來下載和安裝:
C:\>pip3 install xmltodict
Collecting xmltodict
Downloading https://files.pythonhosted.org/packages/28/fd/30d5c1d3ac29ce229f6bdc40bbc20b28f716e8b363140c26eff19122d8a5/xmltodict-0.12.0-py2.py3-none-any.whl
Installing collected packages: xmltodict
Successfully installed xmltodict-0.12.0
導(dǎo)入該模塊后,在代碼中使用xmltodict.parse(xml_str)進(jìn)行處理,這將把xml格式字符串轉(zhuǎn)換為字典格式的數(shù)據(jù),再配合json模塊的dumps()函數(shù),將字典轉(zhuǎn)換為json格式的字符串。
import xmltodict import json # xml to json def xmlToJson(xml_str): try: json_dict = xmltodict.parse(xml_str, encoding = 'utf-8') json_str = json.dumps(json_dict, indent = 2) return json_str except: pass # json to xml def jsonToXml(json_str): try: json_dict = json.loads(json_str) xml_str = xmltodict.unparse(json_dict, encoding = 'utf-8') except: xml_str = xmltodict.umparse({'request':json_dict}, encoding = 'utf-8') finally: return xml_str # load xml file def load_json(xml_path): # 獲取xml文件 xml_file = open(xml_path, 'r') xml_str = xml_file.read() # 將讀取的xml字符串轉(zhuǎn)換為字典 json_dict = xmltodict.parse(xml_str) # 將字典轉(zhuǎn)換為json格式的字符串 json_str = json.dumps(json_dict, indent = 2) return json_str
“Python怎么將xml格式轉(zhuǎn)換為json格式”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
本文題目:Python怎么將xml格式轉(zhuǎn)換為json格式-創(chuàng)新互聯(lián)
鏈接分享:http://www.dlmjj.cn/article/cscdes.html