[英]JSON object mapper for Python
基本上我正在自動化 python 中的 API,API 返回 Z0ECD11C1D7A287401D148A23BBD7A2 F 看起來像下面的響應
在 java 中,我可以使用 POJO Model 驗證架構,使用 Gson lib 就像休閑一樣 -
GetCustomerModel - is my custom POJO class have so 3 inner classes.
GetCustomerModel body = new Gson().fromJson(response.getBody(),GetCustomerModel.class);
Python 中是否有任何庫支持來做同樣的事情,我的意思是將 json 轉換為自定義 python 映射 ZA8CFDE6331C49EB2ACZ6F966
[{
"businessUnit": {
"code": "27888",
"type": "LSCCC"
},
"timeWindows": [
{
"freeCapacity": true,
"capacityTemplateIdentifier": "xxxxxxxxxxxx",
"cutOff": "2020-11-30T17:00:00Z",
"end": "2020-11-30T17:00:00Z",
"maxCapacity": 0,
"start": "2020-11-30T08:00:00Z",
"timeWindowIdentifier": "yyyyyyyyyyyyyy",
"tspId": "9900001"
}
],
"timeZone": "Europe/London"
}]
Python Model -
from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
from typing import List
@dataclass
class BusinessUnit:
code: int
type: str
@dataclass
class TimeWindow:
free_capacity: bool
capacity_template_identifier: str
cut_off: datetime
end: datetime
max_capacity: int
start: datetime
time_window_identifier: UUID
tsp_id: int
@dataclass
class WelcomeElement:
business_unit: BusinessUnit
time_windows: List[TimeWindow]
time_zone: str
我的代碼 -
result = from_dict(data_class=WelcomeElement, data=response.content)
給出錯誤提示 - “元組索引必須是整數或切片,而不是 str”
下面的代碼有效:
需要改進的幾點:
使用類型掛鈎來轉換數據類型
from dataclasses import dataclass from datetime import datetime from uuid import UUID from typing import List from dacite import from_dict @dataclass class BusinessUnit: code: int type: str @dataclass class TimeWindow: free_capacity: bool capacity_template_identifier: str cut_off: str end: str max_capacity: int start: str time_window_identifier: str tsp_id: int @dataclass class WelcomeElement: business_unit: BusinessUnit time_windows: List[TimeWindow] time_zone: str data = [{ "business_unit": { "code": 27888, "type": "LSCCC" }, "time_windows": [ { "free_capacity": True, "capacity_template_identifier": "xxxxxxxxxxxx", "cut_off": "2020-11-30T17:00:00Z", "end": "2020-11-30T17:00:00Z", "max_capacity": 0, "start": "2020-11-30T08:00:00Z", "time_window_identifier": "yyyyyyyyyyyyyy", "tsp_id": 9900001 } ], "time_zone": "Europe/London" }] print('start') result = from_dict(data_class=WelcomeElement, data=data[0]) print(result)
output
start WelcomeElement(business_unit=BusinessUnit(code=27888, type='LSCCC'), time_windows=[TimeWindow(free_capacity=True, capacity_template_identifier='xxxxxxxxxxxx', cut_off='2020-11-30T17:00:00Z', end='2020-11-30T17:00:00Z', max_capacity=0, start='2020-11-30T08:00:00Z', time_window_identifier='yyyyyyyyyyyyyy', tsp_id=9900001)], time_zone='Europe/London')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.