我需要解析一个Json,比如:
{
"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"
}对于这个XML:
<ingresarOrdenBilateral
agente="150" idOrigen="10039" fechaOrigen="2018-08-16T11:28:08.495-03:00" tipo="V"
instrumento="AA17" tipoVenc="24" cantidad="1000000" precio="1625" formaOp="C"
ejecucion="SINCRONICA"/> 我已经尝试过xmltodict和dicttoxml库,但是我无法使用属性而不是元素来获得XML。此外,我认为XML格式是不标准的。
谢谢!
发布于 2021-10-09 19:22:57
嗯,可以用内置的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数据,则可以将json.load()/json.loads()/requests.Response.json().的str()传递给parse_int参数它将强制将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))还有parse_float和parse_constant,您可以以同样的方式使用它们(如果需要的话,ofc)。
发布于 2021-10-09 07:34:14
首先,使用属性而不是子元素是这种结构的完全标准。它可能比使用子元素要少一些,但它并不特别,当然也不是不标准的。
其次,JSON和XML之间的标准现成转换器从来没有给你足够的控制权来产生你想要的目标结构。如果您想要一种特定的XML格式,那么您必须准备好对结果进行转换,这通常很容易用XSLT实现。
如果使用XSLT3.0,则可以在单个样式表中执行JSON到XML的转换和随后的转换;但否则,使用您最喜欢的库转换器,然后是XSLT (1.0+)转换,就足够简单了。您将发现大量将XML元素转换为属性的样式表示例。
发布于 2021-10-09 17:08:16
如果XML如此简单,下面的代码就能够完成这项工作。
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"
}
xml = '<root>' + ' '.join(f'"{k}"="{v}"' for k,v in data.items()) + '</root>'
print(xml)输出
<?xml version="1.0" encoding="UTF-8"?>
<root>"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"</root>https://stackoverflow.com/questions/69502991
复制相似问题