python中xml数据与json数据互相转化

2018-11-13  本文已影响0人  ryan_ren

最近在项目中需要将xml数据与json数据互相转化,所以专门去查了下资料,顺便做个笔记,以备之后使用。

XML转化为JSON格式

1. 安装xmltodict

pip install xmltodict

2. 使用xmltodict来转化xml数据

import xmltodict, json

o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'

JSON转化为XML格式

1.安装dicttoxml

pip install dicttoxml

2.使用dicttoxml转化

import json
import dicttoxml
jsondict = json.loads(json)
xml = dicttoxml.dicttoxml(jsondict,root=False,attr_type=False)

使用dicttoxml转化的xml中默认会在最外面包含一个<root> ... </root>,使用参数root=False可以去掉这个东西。同时默认的xml中还会包含每个属性的类型,就像<item type="str">,使用参数attr_type=False可以去掉这个东西。

requests请求接收的json数据

requests请求获取的json数据,可以通过

r = requests.get(url)
json = r.json()

获取得到,这样得到的json相当于

r = requests.get(url)
json = json.loads(r.text)

两者效果是一样的,所以只需要再通过dicttoxml转化成xml就行了

xml = dicttoxml.dicttoxml(json,root=False,attr_type=False)
上一篇 下一篇

猜你喜欢

热点阅读