好吧,它可以使用内置的一行来完成xml.etree.ElementTree
:
import xml.etree.ElementTree as ET
data = {
"operacion": "ingresarOrdenBilateral",
"agente": "0062",
"comitente": 7211,
"fechaOrigen": "2021-09-23T16:51:27.873-03:00",
"tipo": "V",
"instrumento": "GD30",
"tipoVenc": "24",
"precio": "100000000",
"cantidad": "1",
"idOrigen": 10699570,
"ejecucion": "SINCRONICA"
}
ET.dump(ET.Element(data.pop("operacion"), {k: str(v) for k, v in data.items()}))
输出:
<ingresarOrdenBilateral agente="0062" comitente="7211" fechaOrigen="2021-09-23T16:51:27.873-03:00" tipo="V" instrumento="GD30" tipoVenc="24" precio="100000000" cantidad="1" idOrigen="10699570" ejecucion="SINCRONICA" />
更新。假设您从文件或服务器加载此 JSON 数据,则可以传递str()
给//的parse_int
参数。它将强制将字段解析为,因此我们可以省略我在上面代码中使用的 dict 理解:json.load()
json.loads()
requests.Response.json()
int
str
import json
import xml.etree.ElementTree as ET
str_data = '''{
"operacion": "ingresarOrdenBilateral",
"agente": "0062",
"comitente": 7211,
"fechaOrigen": "2021-09-23T16:51:27.873-03:00",
"tipo": "V",
"instrumento": "GD30",
"tipoVenc": "24",
"precio": "100000000",
"cantidad": "1",
"idOrigen": 10699570,
"ejecucion": "SINCRONICA"
}'''
data = json.loads(str_data, parse_int=str)
ET.dump(ET.Element(data.pop("operacion"), data))
There're also parse_float
and parse_constant
which you can use in same way (if needed, ofc).