我需要決議一個 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 格式不是標準的。
謝謝!
uj5u.com熱心網友回復:
首先,使用屬性而不是子元素是這種結構的完全標準。這可能比使用子元素少一些,但它并不罕見,當然也不是非標準的。
其次,JSON 和 XML 之間的標準現成轉換器永遠不會給您足夠的控制權來準確地生成您想要的目標結構。如果您想要特定的 XML 格式,那么您必須準備對結果進行轉換,這通常很容易用 XSLT 實作。
如果您使用 XSLT 3.0,那么您可以在單個樣式表中進行 JSON 到 XML 的轉換和后續的轉換;但除此之外,使用您最喜歡的庫轉換器,然后使用 XSLT (1.0 ) 轉換就足夠簡單了。您會發現許多將 XML 元素轉換為屬性的樣式表示例。
uj5u.com熱心網友回復:
如果 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>
uj5u.com熱心網友回復:
好吧,它可以使用內置在一行中完成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的引數json.load()/ json.loads()/ requests.Response.json()。它將強制將int欄位決議為str,因此我們可以省略我在上面的代碼中使用的 dict comprehension:
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_floatandparse_constant您可以以相同的方式使用(如果需要,ofc)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314403.html
